在JavaScript中,如何从其事件函数中访问setTimeout / setInterval调用的id?

时间:2013-06-24 16:28:46

标签: javascript settimeout setinterval

如何从其事件函数内部访问setTimeout / setInterval调用的进程id,因为Java线程可能会访问自己的线程ID?

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

3 个答案:

答案 0 :(得分:8)

该代码将按原样运行,因为setTimeout始终在调用提供的回调之前返回,即使您传递的超时值非常小,为零或为负。

> 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
  

问题是我计划有许多同时安排的匿名操作,因此他们无法从同一个变量加载他们的id。

当然可以。

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

答案 1 :(得分:1)

传递给setTimeout的函数无论如何都不知道这个事实。这不是一个进程ID或线程ID,只是一个奇怪的API决定。

答案 2 :(得分:-1)

// Creates timeout or interval based on parameters:
// timeoutOrInterval: string, 'timeout' or 'interval'
// worker: function, worker with signature function(procRef)
// timeout: int, timeout in ms
// context: optional, window object (default is 'window'), can be a window of an iframe, for istance
// see usage below
function makeTimeoutOrInterval(timeoutOrInterval, worker, timeout, context){
  var isTimeout = (timeoutOrInterval == 'timeout'), method = isTimeout ? 'setTimeout': 'setInterval',id, result = getObjectFor(id = (context || window)[method](function(){
    worker.call(this, (result = getObjectFor(id, isTimeout)));
  }, timeout), isTimeout);
  return result;
  function getObjectFor(id, isTimeout) {
    return {
        getId: function() { return id; },
        cancel: function() {
          if (id) {
            if (isTimeout)
                window.clearTimeout(id);
            else
                window.clearInterval(id);
            id = null;
          }
        }
    };
  }
}

// Usage:
var counter = 0;
var procRefOuter = makeTimeoutOrInterval('interval', function(procRef){
    // procRef - object with two methods: getId() and cancel() - to get and id of a worker process or cancel execution
    console.log(procRef.getId());
    console.log ('Counter: ' + (counter++));
    if (counter == 10) {
        procRef.cancel(); // we can cancel further execution inside the worker
    }
}, 2000);

procRefOuter is exactly the same as procRef explained earlier. Only outside.

console.log(procRefOuter.getId());