Daniel Noel-Davies
Daniel Noel-Davies

Reputation: 557

NodeJS Set Timeout

I'm using the phidgets library to interact with physical devices via nodejs. I've got it all connected physically, all I want to do is ensure my timings for the on/off's are precise.

This would be the issue, as I can't even get things to console.log out properly regarding setTimout's.

Essentially, I'm attempting to do the following:

for ( var i = 0; i < 4; i++ ) {
    setTimeout( function(i){
        console.log('Input: "' + i + '", Executed with timeout of ' + i*1000 + 'ms');
    }(i), i*1000 );
};

But my console just spits out the below, with no timeouts. It's instant.

Input: "0", Executed with timeout of 0ms
Input: "1", Executed with timeout of 1000ms
Input: "2", Executed with timeout of 2000ms
Input: "3", Executed with timeout of 3000ms

Which is far from what I want.

Any ideas as to what's going on?

Upvotes: 4

Views: 5986

Answers (1)

Rishi Diwan
Rishi Diwan

Reputation: 338

You are running the function in your setTimeout call because of the (i)

Change it to

setTimeout( function(i){
            console.log('Input: "' + i + '", Executed with timeout of ' + i*1000 + 'ms');
        }, i*1000, i );

This way you are passing the function 'pointer' into the setTimeout setup with the argument i

PS: All arguments after the time value i*1000 will be passed as arguments to your callback function

Upvotes: 4

Related Questions