Reputation: 2045
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
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
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
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