Google Apps Script Hanging Up (javascript) - javascript

The following Javascript is hanging up. I've been teaching myself Apps Script to sort data on a sheet. My web developer friend and I have been clueless for the last 2 hours as to why this particular script stalls. It just says Running Script forever....
What is happening is that I have a section of a spreadsheet designated as a calendar area which already has a dynamic calendar printed onto it by one of my other functions. For testing purposes I isolated this function and gave it a dummy array, but the function should loop through the calendar, locate the COORDs of the 'date' i.e. 1,2,3,4th and return the coordinates of an empty cell below that date (the place where i will put data into the calendar).
function printCalendarValues(array){
var array = [0,143,534,342,54,1,41,1];
var Calendar_Display_range = recruiter_sheet.getRange('B8:H19');
var Calendar_Display_values = Calendar_Display_range.getValues();
function getCellBelow(day, rangeArray){
for(i=0; i<rangeArray.length; i++){
for(j=0;j<rangeArray[i].length; j++){
if(rangeArray[i][j]==day){
var res = [i+9,j+2];
return res;
};
};
}
};
for(i=0;i<2;i++){ //< ---- THIS IS WHERE IT BREAKS
// If I take the code in this for loop out of it and run it
// only once then it runs as expected. It breaks when I put it in
// this for loop. You can see I only loop twice right now. I
// did that for testing, but i've tried twice, or array.length
// anything other than running it once breaks it.
var cellBelow = getCellBelow(i+1, Calendar_Display_values);
recruiter_sheet.getRange(cellBelow[0],cellBelow[1]).setValue(array[i]);
};
};

You need to either define the variable i at the top of your function.
function printCalendarValues(array){
var i;//Define i - its' value will be undefined
Or you need to add the var keyword inside the for parameters. for (var i = 0, etc Right now, the variable i is a global. The value of i is in the "global scope." Any function that you run will have access to i as it is right now.
When your second for loop calls the getCellBelow function, both the for loop and the function getCellBelow are sharing the variable i. So, i gets set to 1, then function getCellBelow gets called. Then i gets set back to zero. So your for loop will go on forever. It never gets to 1. It is constantly being set back to zero by the getCellBelow function.
for(i=0;i<2;i++){ //i gets set to zero and then incremented to 1
var cellBelow = getCellBelow(i+1, Calendar_Display_values);//function called
Then in function getCellBelow;
for(i=0; i<rangeArray.length; i++){//i is set to zero and until the array lengh
So, i could easily now be greater than one. And your loop for(i=0;i<2;i++){ will stop.
You can see this by adding Logger.log('i: ' + i) statements, and then viewing the Log. In View menu, choose Logs after running the code.
You should define i inside of the function function getCellBelow(day, rangeArray){
Should be:
function getCellBelow(day, rangeArray){
var i;
So, the usage of i inside that function will be confined to the function and not affect any other value of i outside of that function.

Related

Google-Sheets - Break a loop based on cell value

I am currently running a timer based script (once a week) that copies a couple of values from one range (source) to another (target).
The source range is the result of a query based on a import. Thus it goes through multiple calculation steps before displaying the proper result.
Usually this should be an easy task - just add a sleep timer to be sure and be done with it.
However, the script copies the data based on an unfinished calculation.
Here's how I approached the this:
I setup a cell that checks if the data was correctly copied (trigger cell)
Now, I could just run a timer on sunday every hour or so, checking if the trigger is true or false. But I was wondering if there is a way to do this with a loop.
I am fairly new to javascript so I'm not very confident with implementing possible solutions from the web.
It seems that loops can only be broken based on values within the loop. A do/while (while 'trigger' == false) loop for example just loops for 5 Minutes until it times out. I think a function call with the function calling itself should do the trick, but I couldn't figure out how to do this properly. My version just seems to run once and break - even when I change the triggervalue manually to force a loop.
function looper(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("example");
var trigger = sheet.getRange("a1").getValue();
var source = sheet.getRange("b1:j1").getValues();
var target = sheet.getRange("b2:j2");
Utilities.sleep(5000)
if (trigger == false){
target.setValues(source);
looper;
}
}
In JavaScript, to call a function you need to use parentheses. So for the last line, try doing this: looper(); instead.

Javascript - How to run part of the code only after the page refreshes?

Important: Even though this could probably be done with php (I'm using WooCommerce on Wordpress), I want this script to run only on my browser. That's why I want to do it in Javascript. Hence, I'm using Custom Javascript for Websites to load my script from my browser.
What my script should do: Check if the data of a specific element has been changed.
Logic: Step 1) Get and locally remember specific string (order number) of a specific class. Step 2) Refresh the page. Step 3) Again get the specific string (order number) of a specific class. Step 4) If strings do not match, run a function (play an audio).
Problem: After page reloads, the script starts to run again from the beginning. Hence, it results in overriding the stored string. As a result, stored and newly fetched string are always equal.
Question: How do I make the script to run the 3rd step only after refresh so that the stored data doesn't override itself?
Current code:
var OrderIdOld = document.getElementsByClassName("row-title"); // Select every single element with ClassName "row-title"
var x = (OrderIdOld[0].innerText); // Get the string of the first element of the class "row-title"
var compareOld = x.slice(-1); // Get the last element of the string (since it will be a number, we can change the string into a number easily later)
localStorage.setItem("compareOld", compareOld); // Store this element in local storage, so that it can be used after page reloads.
setInterval ("window.location.reload()", 30000); // Reload page every 30 secs.
var remembered = localStorage.getItem("compareOld"); // Assign stored element to a new var.
var n = compareOld.valueOf(); // Turn stored element into a number (for easy comparison later).
var OrderIdNew = document.getElementsByClassName("row-title"); // Select every single element with ClassName "row-title"
var y = (OrderIdNew[0].innerText); // Get the string of the first element of the class "row-title"
var compareNew = y.slice(-1); // Get the last element of the string (since it will be a number, we can change the string into a number easily later)
var m = compareNew.valueOf(); // Turn fetched element into a number (for easy comparison later).
function beep() {
var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJ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A//uQZB4ABZx5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");
snd.play();
} // Function that will play the sound.
if (n!=m) {
beep();
} // Run function if two numbers are not equal.
Additional: I have gathered the parts of the code from various Questions on stackoverflow. Meaning, I have been searching about this topic for the past week. This is my first questions ever. Hopefully I formatted the question so that it easy to understand.
EDIT: The issue has been solved. I used the idea of only running the first step of function on the first load of page. This post helped me to get functionality working https://stackoverflow.com/a/22334768/7929506
The working code looks like this:
function beep() {
window.open('https://www.youtube.com/watch?v=EQ3zPIj2O5k','_blank');
}
if (sessionStorage.getItem("visit") == null) {
var OrderIdOld = document.getElementsByClassName("row-title")[0].innerText.slice(-1).valueOf();
sessionStorage.setItem("OrderIdOld", OrderIdOld);
sessionStorage.setItem("visit", new Date());
setTimeout("window.location.reload()", 10000);
}
else {
var OrderIdNew = document.getElementsByClassName("row-title")[0].innerText.slice(-1).valueOf();
var x = sessionStorage.getItem("OrderIdOld");
if (x==OrderIdNew) {
setTimeout("window.location.reload()", 10000);
}
else {
beep();
var x = sessionStorage.getItem("OrderIdOld");
sessionStorage.removeItem("OrderIdOld");
sessionStorage.removeItem("visit");
setTimeout("window.location.reload()", 10000);
}
}
When you refresh the page first time, you can simply append a flag variable to URL to identify weather its a refresh or a first time load. Based on that, you can pass a localized variable to script and if that is set then you need to refresh else not.

JavaScript stack, LIFO stack: value not as expected

I have the following code.
var stackMapIn = [];
var stackMapOut = [];
var stackBack = [];
stackMapOut.push("m1");
$scope.clickLinks = function(initialOut,initialIn,extra,backIn,backOut,name){
$('div#'+initialOut+'Map,'+extra).fadeOut('slow',function(){
$('.'+initialOut+'Details,.bkbtn'+backOut).css("display","none");
$('.'+initialIn+'Details,.bkbtn'+backIn).css("display","block");
$('.noQuery').css("display","none");
$("#buildingHeader").html(name);
$('div#'+initialIn+'Map').fadeIn('slow');
})
stackMapOut.push(initialIn);
stackMapIn.push(initialOut);
stackBack.push(backIn);
}
$scope.clickBack = function(bkbtnCheck){
alert(stackBack[0]);
mapOut = stackMapOut.pop();
mapIn = stackMapIn.pop();
stackBack.pop();
backIn = stackBack[0];
alert(backIn);
$('div#'+mapOut+'Map').fadeOut('slow',function(){
$('.'+ mapOut + 'Details,.bkbtn').css("display", "none");
$('.' + mapIn + 'Details,.bkbtn'+backIn).css("display", "block");
$(".noQuery").css("display","none");
$("#buildingHeader").html("Name");
$('div#' + mapIn + 'Map').fadeIn('slow');
})
}
Now I am going to do a quick run-through of what happens as this code runs.
The first time clickLinks runs:
initialIn = 'm2'
initialOut = 'm1'
backIn = 'Home'
clickBack has not run yet.
The second time clickLinks runs:
initialIn = 'm7'
initialOut = 'm2'
backIn = 'CentralPortfolio'
Ok so at this point things should be looking like this (I expect):
stackMapOut = ['m1','m2','m7']
stackMapIn = ['m1','m2']
stackback = ['Home','CentralPortfolio']
Now we run clickBack... Why does the alert output "Home"??
What I am trying to do here is, I have a series of things appearing and disappearing when clickLinks runs. Sometimes, the user can run clickBack in order to return to the previous state(status). So, I am using JavaScript stack to keep track of what state it is on and thus where it needs to return.
The problem is, I can run clickLinks once, clickBack once consecutively without issue. I can even run clickLinks a second time and still click the back button 2 times (to return to start) without issue. But I still don't understand why stackBack[0] (which should be the top of the stack ?) = "Home" at this point instead of "CentralPortfolio".
Because the real problem that I run into is now if I run clickLinks a third time: still stackBack[0] = 'Home' (when I expect it to be 'CentralCampus' at this point) and thus, it is the "Home" back button that is showing (while the correct other stuff is showing in accordance to mapOut and mapIn) instead of CentralPortfolio' back button to be showing; since I have 'CentralCampus' "popped" off before I use it.
Please, if any other information is needed or you need more clarification let me know. I tried my best to provide any needed information and make it as clear as possible.
Now we run clickBack... Why does the alert output "Home"??`
because stackBack[0] is Home. What would you expect it to do? You even have it in your question:
stackback = ['Home','CentralPortfolio']
The index 0 is the first element in your array, which is Home. The last element is stackBack[stackBack.length - 1]
using JavaScript stack
No, you are using a javascript array, but using it like a stack. Except when you index it like an array - which is the root of your confusion. You can use it as a stack with pop and push, but then don't try and index it with []
When you push on an array, you add an element to the end of the array. In other words, it ends up as the last element at the index yourArray.length - 1. When you pop, you take that last element off the array again. So popping stackback would give you back CentralPortfolio, and, of course, the first element is unchanged.

Accessing values in javascript

I am using a JS library for facetracking/emotion detection called CLMtracker.
http://auduno.github.io/clmtrackr/examples/clm_emotiondetection.html
Note: Seems to work best in chrome for those trying to use it.
Is the example I am using, I am wondering how I can access the values for each emotion. For instance, I want check every 10 seconds what the values are and print to console. From this I would also like to compare the values to find the highest and find the emotion that is attached to that. I think I am right in saying that the max() function will give me the highest out of an array?
What I have tried:
I have tried to get emotionData[0].emotion and emotionData[0].value which should print Angry and the value, but it only prints 0. I have also tried the same method with data which does not seem to return anything.
EDIT
emotionData gets me:
however it does not seem to show any update/change as I make my expression change
ec.meanPredict(ctrack.getCurrentParameters()) returns an object containing all the current scores for all emotions.
To get the current score of "Angry", for example, you would do :
ec.meanPredict(ctrack.getCurrentParameters())[0].value
So, in order to get the current most probable emotion, you could do this :
function getCurrentEmotion()
{
if(!ec.meanPredict(ctrack.getCurrentParameters())){setTimeout(getCurrentEmotion,1000);return;}
var currentData = ec.meanPredict(ctrack.getCurrentParameters());
var currentScores = [];
//Gather all scores in an array
for(var i=0;i<currentData.length;i++)
{
currentScores.push(currentData[i].value);
}
//Get the biggest score
var max = Math.max.apply(null,currentScores);
//Calculate its index
var indexOfScore = currentScores.indexOf(max);
//Get the associated emotion
var emotion = currentData[indexOfScore].emotion;
console.log(emotion);
//Set up a loop (did not add 'var', to allow stopping it from outside)
currentEmotionLoop = setTimeout(getCurrentEmotion,3000);
}
To stop the loop at any time, do this :
clearTimeout(currentEmotionLoop);
By the way, the ec variable is declared privately, so in order for this to work, either remove var where it is declared :
var ec = new emotionClassifier();
or write this code in the same file, under the same scope.

Javascript weird variable connection / behaviour with each other

I've been programming in javascript (with a support from jquery) and I've run into some weird variable behaviour, which in I think is truly unexpected (or maybe I don't know something).
Basically, what I wanna do is to have one variable (zodziai) (array) be "stuffed" with arrays in one part of code and later on have those arrays removed by a click of buttons (one by one).
Also I still want to have those arrays saved in the end of the game even if the first variable is empty because of the button clicks.Easy, I thought to myself, so I've created another array variable (zodziai2) and equated those both in the beginning of the game (when the first one is full of arrays, ready to have them removed one by one.
Everything seems to fine until I check the value of zodziai2, second variable, in the end of the game. Even if it hasn't been touched throughout the process of removing elements from zodziai (first variable), somehow it turns out to be empty too in the end of the game.
Code: I declared both variable inside document.ready as = [];
$("#begin").click(function() {
//#begin is a button which starts the game
$("#enterwords").html("It's showtime!");
zodziai2 = zodziai; //zodziai is full of stuff, making zodziai2 the same
alert(window.zodziai2); //checking, zodziai2 seems to be equal to zodziai
taskai = 0;
maxtaskai = zodziai.length;
...
if (zodziai.length > 0) {
... stuff, just DOM.
...
}
});
And there goes the next button, which is responsible for removing one item from zodziai array. Somehow it gets removed from zodziai2 too.
$("#next").click(function() {
enword = $("#angliskas_zodis").val();
ltword = $("#lietuviskas_zodis").val();
//enword = enword.split("");
//atitinkamas = atitinkamas.split("");
if (enword == atitinkamas) {
...
zodziai.remove(random_skaicius); // removing one item from zodziai (no worries, it's a self written function, working as a bee
...
...
});
Later on, I define the third button, restart, in which zodziai2 is now empty as is zodziai. How can zodziai2 be empty if the code is only "playing" with zodziai? What am I missing??
$("#restart").click(function() {
zodziai = zodziai2; //should be full of stuff, but is certainly not :(
random_skaicius = 0;
ilgis = 0;
zodis = "";
atitinkamas = "";
tempzodislt = "";
taskai = 0;
maxtaskai = 0;
klaidingi = [];
$("#angliskas_zodis").val("");
$("#lietuviskas_zodis").val("");
surasymas(window.zodziai2);
alertify.alert("Drop us a line if you think this function would be useful :)");
});
Just a pointer. I see you write a statement zodziai2 = zodziai. What it means that both variables point to the same memory location of the array. If you remove an element from zodziai, it'll be removed from zodziai2 too. Does this helps?

Categories