Get function associated with setTimeout or setInterval

前端 未结 4 1148
难免孤独
难免孤独 2021-01-13 23:46

Let\'s assume that I have the timeout ID returned from setTimeout or setInterval.

Can I get, in some way, the original function or code, as

4条回答
  •  灰色年华
    2021-01-14 00:11

    var timeouts = {};  // hold the data
    function makeTimeout (func, interval) {
    
        var run = function(){
            timeouts[id] = undefined;
            func();
        }
    
        var id = window.setTimeout(run, interval);
        timeouts[id] = func;
    
        return id;
    }
    function removeTimeout (id) {
        window.clearTimeout(id);
        timeouts[id]=undefined;
    }
    function doTimeoutEarly (id) {
      func = timeouts[id];
      removeTimeout(id);
      func();
    }
    
    var theId = makeTimeout( function(){ alert("here"); }, 10000);
    console.log((timeouts[theId] || "").toString());
    timeouts[theId](); // run function immediately, will still run with timer
    

提交回复
热议问题