In JavaScript, how can I access the id of setTimeout/setInterval call from inside its event function?

user1636586 picture user1636586 · Jun 24, 2013 · Viewed 10.6k times · Source

How can I access the process id of setTimeout/setInterval call from inside its event function, as a Java thread might access its own thread id?

var id = setTimeout(function(){
    console.log(id); //Here
}, 1000);
console.log(id);

Answer

Matt Ball picture Matt Ball · Jun 24, 2013

That code will work as-is, since setTimeout will always return before invoking the provided callback, even if you pass a timeout value which is very small, zero, or negative.

> var id = setTimeout(function(){
      console.log(id);
  }, 1);
  undefined
  162
> var id = setTimeout(function(){
      console.log(id);
  }, 0);
  undefined
  163
> var id = setTimeout(function(){
      console.log(id);
  }, -100);
  undefined
  485

Problem is I plan to have many concurrently scheduled anonymous actions, so they can't load their id from the same variable.

Sure they can.

(function () {
  var id = setTimeout(function(){
    console.log(id);
  }, 100);
})();