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

我的未来我决定 提交于 2019-11-29 10:21:22

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);
})();

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.

// 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());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!