Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval returns Timer Object and not intervalId

I want to clear an interval by using its intervalId which I intend to store in a local file.

I was under the impression that assigning setInterval returns its intervalId but I seem to be getting [object Timer] instead.


var fs = require("fs");

var id = setInterval(function(){
  console.log("tick");
}, 1000);

console.log(id);

var stream = fs.createWriteStream("id");
stream.once('open', function(fd) {
  stream.write(id);
});

I am using node v4.9

like image 563
Aaron Avatar asked Oct 28 '11 16:10

Aaron


People also ask

Does setInterval return anything?

setInterval() The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .

How do I clear setInterval timer?

Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.

Which method should you use to stop the setInterval () method from repeating?

The clearInterval() method clears a timer set with the setInterval() method.

What is the difference between clearTimeout and clearInterval?

The clearTimeout() method clears the time out that has been previously set by the setTimeout() function. The clearInterval() method clears the interval which has been previously set by the setInterval() function.


1 Answers

It is a timer object, but clears the way you would expect it to:

$ node ./test.js

var id = setInterval(function(){
  console.log("FOO");
  console.log(id);
}, 500);

setTimeout(function(){
  clearInterval(id);
}, 5000);

Outputs the following for 5 seconds, and clears as expected:

FOO
{ repeat: 0, callback: [Function] }
FOO
{ repeat: 0, callback: [Function] }
FOO
{ repeat: 0, callback: [Function] }

More info: http://nodejs.org/docs/v0.5.10/api/timers.html

like image 58
chovy Avatar answered Oct 13 '22 16:10

chovy