TransWikia.com

Why does this javascript sleep function skip immediately?

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.

4 Answers

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:

  1. Set isPaused to false
  2. Define the sleep function (not execute it)
  3. log "here"
  4. Set isPaused to true
  5. Execute the sleep function, it will be called again after 1000ms, but the program doesn't wait for this, so it already executes the next line.
  6. log "here 2"

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

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP