Get function associated with setTimeout or setInterval

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

    You can store each timeout function in an object so that you can retrieve it later.

    var timeout_funcs = {};
    
    function addTimeout(func,time) {
        var id = window.setTimeout(func,time);
        timeout_funcs[id] = func;
        return id;
    }
    
    function getTimeout(id) {
        if(timeout_funcs[id])
            return timeout_funcs[id];
        else
            return null;
    }
    
    function delTimeout(id) {
        if(timeout_funcs[id]) {
            window.clearTimeout(timeout_funcs[id]);
            delete timeout_funcs[id];
        }
    }
    

提交回复
热议问题