Skip to content

how to stop other code from executing while set timeout is executing?

This question is duplicate of How to stop other code from running until setTimeout() finishes running?

In the above question the person does not want any code to be executed until the setTimeout function has been executed. So that function never get executed. But here in my case I want the code after the setTimeout to execute.(after setTimeout has finished executing)

BUt it’s not working for me. Here is the code :

console.log("Hello Wolrd");

var prev_exe = false;
setTimeout(function(){
    console.log("Hello Again");
    prev_exe = true;
}, 3000)

function bye() {
    if(!prev_exe) {
        return;
    }
    console.log("Gud Bye");
}

bye();

I expect the output to be : Hello wolrd Hello again gud bye

But that is not happening, instead the code just run the first tow console.log() statements and the third is ignored.

Pls help me understand what is wrong with my code .

Answer

You don’t want to stop other code from running, you want to make other code wait to run – so the if (!prev_exe) { return isn’t the logic you need, since that’ll mean Gud Bye never gets logged.

Consider constructing a Promise from the timeout instead, and call .then on it:

console.log("Hello Wolrd");

const againProm = new Promise((resolve) => {
    setTimeout(function(){
        console.log("Hello Again");
        resolve();
    }, 3000);
});

function bye() {
    console.log("Gud Bye");
}

againProm.then(bye);