Bunty
Bunty

Reputation: 21

Why does setTimeout not trigger after specified time

I am running a very basic javascript code in Viusal Studio Code. However I am not seeing the callback function get triggered.

I am trying to understand how setTimeout() works in javascript. I am running the following code (in file called test.js) in Visual Studio code as follows:

node test.js

'use strict'

let timerexpired = false;
setTimeout( function() {console.log(`setting timerexpired to true...`);
                        timerexpired = true;
                        }, 
                        5000);

while(1) {
    console.log(`timerexpired = `, timerexpired);

    if (timerexpired) {
        console.log(`timer expired.  Resume execution`);
        break;
    } else {
        console.log(`keep on spinning`);
    }

}

Expect the loop to break after 5000 ms. But it keeps on spinning with output as "keep on spinning"

Upvotes: 0

Views: 3332

Answers (2)

Hamza El Aoutar
Hamza El Aoutar

Reputation: 5657

When you call setTimeout or when you do any blocking operation for that matter, it's in fact added to an event table and not executed immediately.

It's only after the call stack is empty that the event loop check the event table to see if there's anything waiting, and move it to the call stack.

To better understand this, check the following example:

setTimeout(() => console.log('first'), 0)
console.log('second')

You may think that first will be logged before second, but in fact it's second that will be logged first.

In your example the call stack is never empty, so setTimeout won't really work as expected.

You may wanna check this, it will give you a better idea about what's happening under the hood.

Upvotes: 5

Damini Ganesh
Damini Ganesh

Reputation: 308

While(1) is an infinite while loop. I think that is the reason

Upvotes: 1

Related Questions