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
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 usesetIntervalwith a small timeout instead ofwhile(true).