Stack Overflow Asked by Getwrong on December 25, 2021
Where isPaused becomes true, the sleep function should go into an infinite loop right??? but for some reason it does not, instead it will print "here2" immediately after? i am using this with an async function which when it is done the bool isPaused becomes false again.
var isPaused = false;
function sleep() {
if (isPaused == true) {
setTimeout(function(){sleep()},1000);
}
};
console.log("here");
isPaused = true;
sleep();
console.log("here 2");
how can i fix it so it will wait, instead of continuing.
If you want to wait for the timer, you need to use a Promise
with async
and await
:
(async () => {
var isPaused = false;
setTimeout(function() {
isPaused = false;
}, 3000);
async function sleep() {
if (isPaused == true) {
await new Promise(resolve => {
setTimeout(async function() {
await sleep();
resolve()
}, 1000);
});
}
return;
}
console.log("here");
isPaused = true;
await sleep();
console.log("here 2");
})();
Here is a JSFiddle.
Answered by Daemon Beast on December 25, 2021
That's already an infinite loop. Just try to add an "console.log('loop')" inside the setTimeout function and you will see how it's called each second.
Also, remember javascript is not syncronous, so it will print here 2 before the sleep (remember, it requires 1 sec), but it keep working in the infinite loop
Answered by alfouz on December 25, 2021
Your code will run the sleep function, then run it again after 1000 milliseconds.
What your code does:
Answered by Epic Martijn on December 25, 2021
Because the function sleep is done setting the timeout, so the code can then continue the rest of the operations.
Then after having continued operations for 1s (1000ms) it will perform another sleep, after which it is free to run any other potentially remaining operations.
So the infinite loop does happen, it just doesn't prohibit other code from running. Try putting a console.log('test') in the first line of the sleep function.
function sleep() {
console.log("test")
if (isPaused == true) {
setTimeout(function(){
sleep()
},1000);
}
};
A little too much to get into here, and others can explain a lot better than me, but look into the JS Event Loop, that should clarify some things!
Answered by Rick on December 25, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP