Fei Xue
Fei Xue

Reputation: 2045

How to trigger timeout function in Node.js?

I want to trigger the setTimeout callback function, but it seems not work. What's the problem?

var fs = require("fs");

// set timeout callback
setTimeout(function(){
    console.log("5000ms timeout");
    process.exit(0);
}, 5000 );

// do something more than 5000ms
while(true) {
    var stats = fs.statSync("foo");
    console.log("while statement running...");
}

when I run this, after 5s, the program is still running

Upvotes: 2

Views: 1381

Answers (3)

SLaks
SLaks

Reputation: 887195

Javascript is strictly single-threaded. (except for workers)

As long as your while loop is running, no other Javascript code can execute at all, including your setTimeout callback.

By contrast, calling setInterval simply schedules a callback to run periodically, but doesn't block the thread in the interim.

Upvotes: 1

Erik  Reppen
Erik Reppen

Reputation: 4635

I'm not familiar with node.js but I would normally expect the while loop to keep running. JS is blocking. In order to stop that loop, it's condition needs to evaluate as false. Until the loop stops, nothing else will execute.

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359776

The while(true) is a tight spin loop which prevents any other asynchronous callbacks from firing. Don't do this in a single-threaded environment. You can use setInterval with a small timeout instead of while(true).

Upvotes: 2

Related Questions