Getwrong
Getwrong

Reputation: 187

Why does this javascript sleep function skip immediately?

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.

Upvotes: 0

Views: 332

Answers (4)

Daemon Beast
Daemon Beast

Reputation: 2909

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.

Upvotes: 2

alfouz
alfouz

Reputation: 106

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

Upvotes: 0

Epic Martijn
Epic Martijn

Reputation: 345

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"

Upvotes: 1

Rick
Rick

Reputation: 338

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!

Upvotes: 0

Related Questions