crazyfox crazyfox -3 years ago 214
Javascript Question

Why does this javascript code not exit cleanly?

When I run this code using node on the command line, it just hangs instead of returning after printing zero. I understand the thing about why "this" is not incrementing "age" because of the function scope changing the reference to "this".

function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;

setInterval(function growUp() {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
}, 1000);

var p = new Person();


Answer Source

It's hanging because setInterval runs asynchronously, and also runs forever. Node (and other command line programs) often buffer output and don't print it immediately, sometimes even waiting until the app is ready to terminate. That's probably what is happening in this case.

Try changing setInterval to setTimeout and see if you get your console log to print then.


As mentioned by cdbajorin, setInterval and setTimeout both return a Timeout object (on Node at least, in browser they return numeric IDs) which you can pass into clearTimeout and clearInterval to cancel them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download