2

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

3 Answers 3

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

that's to say, i cannot break the while statement using setTimeout?
When I use setInterval to repace while(true), it works. So i want to know the While(true) is atomic and we cannot break it using setTimeout ?
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.