从timeoutID获取setTimeout延迟

use*_*531 2 javascript javascript-events settimeout

如何根据超时ID找到超时延迟(如果超时ID不可能,则可能是其他内容,如超时对象等)

timeoutID = window.setTimeout(slowAlert, 2000);
getOriginalTimeoutValue(timeoutId);

function getOriginalTimeoutValue(timeoutId) {
   // find original timeout delay (i.e. 2000)
}
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 7

你不能.API不会公开该信息.你必须自己跟踪它.

var timeout_data = {};
timeout_data.time = 2000;
timeout_data.id = setTimeout(slowAlert, timeout_data.time);
Run Code Online (Sandbox Code Playgroud)


T.J*_*der 6

如何根据超时ID找到超时延迟(如果超时ID不可能,则可能是其他内容,如超时对象等)

你根本不可能.任何浏览器API都不提供该信息.你可以编写一个包装setTimeout来做它(甚至可以替换默认的包装),但它不是开箱即用的东西.

你自己的功能的快速和脏版本可能看起来像这样(我坚持使用ES5级别的东西,所以没有Map),但一定要让它进行代码审查,这只是简单的:

(function(global) {
    // For our active timers
    var timers = {};
    // setTimeout wrapper with one that remembers the ID and delay
    global.mySetTimeout = function(callback, delay) {
        // Grab any args passed after delay
        var args = Array.prototype.slice.call(arguments, 2);
        var timer = setTimeout(function() {
            // Forget the ID
            delete timers[timer];
            // Call the callback
            return callback.apply(null, args);
        }, delay);
        timers[timer] = delay;
        return timer;
    };
    // clearTimeout wrapper to delete our record
    global.myClearTimeout = function(timer) {
        delete timers[timer];
        clearTimeout(timer);
    };
    // Create a new global function to get the delay
    global.getTimeoutDelay = function(timer) {
        return timers[timer];
    };
})(this);
Run Code Online (Sandbox Code Playgroud)

或者如果你真的需要替换全局函数(通常不是一个好主意):

(function(global) {
    // For our active timers
    var timers = {};
    // The original functions
    var origSetTimeout = setTimeout;
    var origClearTimeout = clearTimeout;
    // Replace setTimeout with one that remembers the ID and delay
    setTimeout = function(callback, delay) {
        // Grab any args passed after delay
        var args = Array.prototype.slice.call(arguments, 2);
        var timer = origSetTimeout(function() {
            // Forget the ID
            delete timers[timer];
            // Call the callback
            return callback.apply(null, args);
        }, delay);
        timers[timer] = delay;
        return timer;
    };
    // Replace clearTimeout to delete our record
    clearTimeout = function(timer) {
        delete timers[timer];
        origClearTimeout(timer);
    };
    // Create a new global function to get the delay
    global.getTimeoutDelay = function(timer) {
        return timers[timer];
    };
})(this);
Run Code Online (Sandbox Code Playgroud)

只是一个开始(并且未经测试),您可能会发现 - 至少 - 您也想要处理clearInterval(因为它可以清除设置的计时器setTimeout).