Robinlemon Robinlemon - 3 months ago 9
Node.js Question

Parsing setInterval ID's to it's parameter function

I'm going to be executing lot's of setIntervals, there's a way to make it more efficient; but that's down the road.

Is there a way I can do this?

var a = setInterval(function(a){
console.log(a);
clearInterval(a);
}, 1000, a);


So the ID is parsed into the function itself, this way I wont have to store the ID to clear it again.

Answer

You have two options here.

Recursive setTimeout:

function doTheJob() {
  console.log("I'm working")
  setTimeout(doTheJob, 1000)
}

Simple setinterval with leaving the variable(id) in scope:

var id = setInterval(function() {
  console.log("I'm working")

  if( something ) 
    clearInterval(id)   
}, 1000)