Get function associated with setTimeout or setInterval

前端 未结 4 1110
难免孤独
难免孤独 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:10

    the IDs returned from setTimeout/setInterval are just numbers, they have no properties or methods other than those that every other number would have. If you want to get that function, you can declare it first instead of using an anonymous:

    var myFunc = function() {
        console.log('Hello Stackoverflowers!');
    };
    
    var timer_id = setTimeout(myFunc, 100000);
    
    myFunc(); // output: 'Hello Stackoverflowers!'
    
    clearTimeout(timer_id); // unless you want it to fire twice
    

提交回复
热议问题