What is setTimeout callback not getting called issue?

Consider the below code.

  • In this code as well, we are trying to setTimeout for 3 seconds, which should raise an alert as soon as timeout is done after 3 seconds.
  • Now after the timeout is done, we are doing some operation (lets say empty loop) for some time, as shown in the code.

Javascript




<script>
    startTime = new Date().getTime();
    setTimeout(function gfgCallback() {
        endTime = new Date().getTime();
        alert(`This function is executed after ${Math.floor((endTime - startTime) / 1000)} seconds`);
    }, 3000);
     
    // The below code is to simulate the execution
    // of millions of lines of code which blocks the
    // Call Stack of a large period of time
    while(new Date().getTime() - startTime < 9000) {
        // Do nothing
    }
</script>


Expected Output:

Actual Output:

GFact | Why setTimeout callback doesn’t get called or work?

Every JavaScript Developer must have used setTimeout() method to execute some code after a particular interval of time (let’s say T milliseconds). But more often you might have come across the issue that nothing happens when the setTimeout is invoked, or the setTimeout goes into an infinite loop. In this edition of GFact, we will deep dive into this and understand what happens behind the scenes of setTimeout callback and why doesn’t it get called as expected.

Similar Reads

What is setTimeout() callback method?

The setTimeout() method sets a timer that executes a function or specified piece of code once the timer expires....

What is setTimeout callback not getting called issue?

...

Why doesn’t setTimeout() callback not get called after 3 seconds as mentioned in the code?

Consider the below code....

Does setTimeout() guarantee the execution of the code inside the callback function gfgCallback() after exactly T milliseconds?

...