Sphinx
Sphinx

Reputation: 109

Placing timer ID into its function

I would like to put timer ID, returned by setInterval(), into its function:

delay_timeout = setInterval(function () {
    test_delay(data['time'], delay_timeout);
}, 1000);

Is it possible? To my mind delay_timeout doesn't have a value at this point...

I don't want to save delay_timeout globally for using later in timer's function to stop it. Several timers may work at the same time.

UPDATE:

Code is not global, it is located here:

socket.on('test_delay', function (data) {
    ...
});

The point is not to make delay_timeout global and be able to kill timer by some condition within its callback function.

Upvotes: 1

Views: 526

Answers (1)

jaybeeuu
jaybeeuu

Reputation: 1123

your code works fine if you put the setTimeout call in it's own function like this:

function setTimer(){
    var timeId = setTimeout(function(){ console.log(timeId); }, 1);
}

for(var i = 0; i < 10; i ++){
    setTimer();
}

here's a fiddle

The delay_timeout variable is available to your callback as it is in the same enclosure.

So long as you are not in the same context and rerun your setTimeout before it has triggered the callback you will be fine. so this won't work:

var timeId;

for(var i = 0; i < 10; i ++){
     timeId = setTimeout(function(){ console.log(timeId); }, 1);
}

(see the second half of the fiddle...)

Upvotes: 1

Related Questions