14

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);
JaskeyLam
  • 15,405
  • 21
  • 114
  • 149
user1636586
  • 171
  • 1
  • 1
  • 7

2 Answers2

14

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);
})();
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 1
    Problem is I plan to have many concurrently scheduled anonymous actions, so they can't load their id from the same variable. – user1636586 Jun 24 '13 at 16:53
  • 2
    @user1636586 So push their ids into an array and iterate through the array to clear them. – Racheet Jun 24 '13 at 17:05
  • 1
    @user1636586 there's a simple fix for that. See my edit. – Matt Ball Jun 24 '13 at 17:14
  • 1
    Who's talking about clearing them? I just want to be able to announce these actions by id as they are run. – user1636586 Jun 24 '13 at 17:15
  • //It seems if I deploy my timers from different execution blocks I can get the result I want. (function(){ var id = setTimeout(function(){ console.log(id); }, 3000); console.log(id); })(); (function(){ var id = setTimeout(function(){ console.log(id); }, 2000); console.log(id); })(); (function(){ var id = setTimeout(function(){ console.log(id); }, 1000); console.log(id); })(); – user1636586 Jun 24 '13 at 18:23
  • @user1636586 that's precisely what I meant by my edit. – Matt Ball Jun 24 '13 at 18:25
1

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.

Esailija
  • 138,174
  • 23
  • 272
  • 326
  • 2
    It's not a weird API decision at all. It's a handle for canceling the timeout later. – Matt Ball Jun 24 '13 at 16:33
  • 4
    Yes it's not weird API that you can cancel all timeouts by doing `var l = 100000; while(l--) clearTimeout(l)`. Even with heaviest wrappers you can't fix it. – Esailija Jun 24 '13 at 16:34