This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm trying to define a global variable value, from a function which is executed with the timeout method. The problem I'm facing here is can't get rid of the time interval.
*** Not Working (But I want the goal variable to be outside so that I can access it later).
function demo() {
var noOfGoals = 4;
goal = "He has scored " + noOfGoals + " in 45 Mins";
}
setTimeout(function() {
demo();
}, 2000);
console.log(goal);
****Working(but I dont want to access it from setTimeout)
function demo() {
var noOfGoals = 4;
goal = "He has scored " + noOfGoals + " in 45 Mins";
}
setTimeout(function() {
demo();
console.log(goal);
}, 2000);
Any new ideas or a better apporach than how have I done!
You can't get a return value from the function you pass to setTimeout.
For what you want to do, that would be written as:
function demo() {
var noOfGoals = 4;
return goal = "He has scored " + noOfGoals + " in 45 Mins";
}
function launch_goal () {
setTimeout(function() {
console.log(demo());
}, 2000);
}
launch_goal();
Or the other way to do it, you will need to use Promises
Related
This question already has answers here:
Combination of async function + await + setTimeout
(17 answers)
Closed 9 months ago.
I've the following code that should have to works for a slider:
let timeOut, timeOut2;
over = 1;
let back = 0;
setInterval(change2, 8000);
async function change2() {
innerFront = slides[over];
innerBack = slides[back];
await setTimeout(change, 8000);
innerFront.querySelectorAll('figure')[0].classList.remove('isActive');
innerFront.classList.remove('slideshow__inner--front');
innerBack.querySelectorAll('figure')[0].classList.remove('isActive');
innerBack.classList.remove('slideshow__inner--back');
over -= 1;
if (over < 0) over = slides.lenght;
back = over - 1;
if (back < 0) back = slides.lenght;
slides[over].classList.add('slideshow__inner--front');
slides[back].classList.add('slideshow__inner--back');
}
function change() {
return new Promise(function(resolve, reject) {
innerFront.querySelectorAll('figure')[0].classList.add('isActive');
timeOut2 = setTimeout(()=> {
innerBack.querySelectorAll('figure')[0].classList.add('isActive');
}, 1000);
resolve();
});
}
My problem consists in the fact that the 'change' function seems not to be performed despite the Await for Promise. In fact, the subsequent instructions are immediately performed, and obviously this generate errors.
I still have doubts about the promises, which I am studying, and here I think there can be something conceptual.
Does anyone have the patience to explain to me where I'm wrong?
There's a typo inside of change2() you wrote lenght instead of length twice.
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
I am trying to pass the variable I get from chrome.storage.local.get to another global variable delayMilliSeconds so I can use it in multiple functions. I know that the delay is only inside the scope of chrome.storage.local.get and is asynchronous, however, is there a way to pass this outside the scope?
var delay;
chrome.storage.local.get('updateDelayValueTo', function(result){
delay = result.updateDelayValueTo; //I am getting this correctly
console.log("delay is: " + delay); //10000
});
function runMyCalculation() {
var delayMilliSeconds = Math.floor((Math.random() * delay) + 1);
// Run other code/functions, which depends on "delayMilliSeconds"
functionOne(delayMilliSeconds);
}
functionOne(delayMilliSeconds) {
//use delayMilliSeconds here
if(functionTwo()){
setTimeout(functionOne,delayMilliSeconds);
console.log("delay in here is: " + delayMilliSeconds);
}
}
functionTwo() {
//and here..
while(ButtonIsClicked){
console.log("delay in here is: " + delayMilliSeconds);
ButtonIsClicked logic...
}
}
console.log
delay down here is: 260
09:36:22.812 content_script.js:83 delay down here is: 260
09:36:22.813 content_script.js:15 delay is: 1000
09:36:23.074 content_script.js:79 delay down here is: undefined
09:36:23.087 content_script.js:83 delay down here is: undefined
09:36:23.089 content_script.js:79 delay down here is: undefined
09:36:23.089 content_script.js:83 delay down here is: undefined
You should set delayMilliSeconds only after have got result.updateDelayValueTo value.
This should work:
var delay;
chrome.storage.local.get('updateDelayValueTo', function(result){
delay = result.updateDelayValueTo;
runMyCalculation();
});
function runMyCalculation() {
var delayMilliSeconds = Math.floor((Math.random() * delay) + 1);
// Run other code/functions, which depends on "delayMilliSeconds"
}
This question already has an answer here:
Maximum call stack size exceeded on SetTimeout recursive function (Javascript) [duplicate]
(1 answer)
Closed 5 years ago.
It says: TypeError: myFunc is not a function
I want the output to be "I am happy, haha!".
I'm learning callback functions in JS.
function emotions(myString, myFunc) {
console.log("I am " + myString + ", " + myFunc(2));
}
var laugh = function(val) {
var ha="";
for(var i=0;i<val; i++) {
ha=ha+"ha";
}
return ha;
};
emotions("happy",laugh(2));
Try this:
emotions("happy", laugh);
You're having that issue because you're no passing the function itself, but it's result as the parameter. When you do laugh() you are running the function, not using it's reference, hence, you're passing it's result instead.
The call will the executed inside the emotions function as laugh(2), so that's the correct way.
function emotions(myString, myFunc) {
console.log("I am " + myString + ", " + myFunc(2));
}
var laugh = function(val) {
var ha="";
for(var i=0;i<val; i++) {
ha=ha+"ha";
}
return ha;
};
console.log(emotions("happy",laugh));
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I always thought that javascript is a single threaded language (for the most part at least).
As you can see in my code:
<html>
<body>
<a onclick="test();">test</a>
</body>
<script>
var text = "test";
function show()
{
console.log("show(): "+ text);
}
function test()
{
console.log("before: "+text);
change();
console.log("after: "+text);
show();
}
function change()
{
text = stateChange(-1);
}
function stateChange(newState) {
var output = "empty";
setTimeout(function () {
if (newState == -1) {
alert('VIDEO HAS STOPPED');
output = "newText";
console.log("AFTER 5 Sec: "+output);
}
}, 5000);
return output;
}
</script>
</html>
My stateChange function returns a variable already prior to completion of the function. It didn't wait 5 seconds before returning the variable to change() function. Therefore, all the functions inside the test() function were being executed (then of course after 5 seconds the alert shows up).
My question is, is there a way to return variable only when the function is fully completed. It seems like it javascript created another thread to execute other functions. Any way to go around this?
(This happens in ajax as well, where I will have a function i thought i will return after the completion of the ajax call, but turns out the function just return itself right away before finishing the ajax call.)
I want my test() function to work in order.
It is because setTimeout() is executed asynchronously, after creating a timer to be executed in the future the calling function will continue executing before the timeout handler is executed.
If you want to wait for 5 seconds and then execute something, then you can use a callback like
var text = "test";
function show() {
console.log("show(): " + text);
}
function test() {
console.log("before: " + text);
change(function(data) {
console.log("after: " + text);
console.log('param', data)
show();
});
}
function change(callback) {
stateChange(-1, function(output) {
console.log('after change', output);
text = output;
callback(text)
});
}
function stateChange(newState, callback) {
var output = "empty";
setTimeout(function() {
if (newState == -1) {
alert('VIDEO HAS STOPPED');
output = "newText";
console.log("AFTER 5 Sec: " + output);
callback(output)
} else {
callback(output)
}
}, 5000);
}
<a onclick="test();">test</a>
How JavaScript Timers Work
The code in the function in the setTimeout call is executed after five seconds have passed. The stateChange function will complete execution after calling setTimeout.
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Javascript setTimeout, Loops and Closure
(1 answer)
Closed 9 years ago.
I got the below code within a callback of xmlHTTPRequest callback function:
// some more code before
...
// schedule the UI update
var totSteps = 6;
for(var i = 0; i < listChangeEl.length; ++i) {
// callback pulse function
var curPulse = function cell_pulse(elName, curCnt) {
console.log("Accessing element: " + elName);
var curEl = document.getElementById(elName);
console.log("Element: " + elName + " = " + curEl);
var curColor = RGB2HTML(255, 255*(curCnt/totSteps), 255*(curCnt/totSteps));
if(curCnt < totSteps) {
// recursion here!
setTimeout( function(){ cell_pulse(elName, curCnt+1); }, 125);
}
};
// start it!
setTimeout( function() { (curPulse)(listChangeEl[i], 0); }, 125);
}
Apparently when the above is setTimeout( function() { (curPulse)(listChangeEl[i], 0); }, 125); is executed , listChangeEl[i] does contain the right id of a cell I want to update, but then, upon first execution of function cell_pulse the parameter elName is undefined.
What am I doing wrong? Does Javascript manage lambda (of lamdba) properly?
Thanks,
Ema