Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 884
user1636586 Avatar asked Jun 24 '13 16:06

user1636586


2 Answers

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);
})();
like image 72
Matt Ball Avatar answered Oct 17 '22 07:10

Matt Ball


The function passed to setTimeout is not aware of the fact in any way. And that's not a process id or thread id, just a weird API decision.

like image 38
Esailija Avatar answered Oct 17 '22 08:10

Esailija