简体   繁体   English

如果参数为“未定义”,为什么“clearTimeout”不会产生错误?

[英]Why doesn't `clearTimeout` produce an error if the argument is `undefined`?

 function getData() { console.log('Fetching data'); } const magic = (fn, delay) => { let timer; return function() { clearTimeout(timer); timer = setTimeout(() => { fn(); }, delay); } } const better = magic(getData, 3000);
 <input type="text" onkeypress="better()" />

For the very first time timer would be undefined then why JavaScript doesn't give an error for that?第一次timerundefined那么为什么 JavaScript 没有给出错误呢?

If you pass an handleid that is not present in the list of active timeouts, then the method ignores it.如果您传递活动超时列表中不存在的handleid ,则该方法将忽略它。 It doesn't throw an error.它不会抛出错误。

The clearTimeout() method must clear the entry identified as handle from the list of active timeouts of the WindowTimers object on which the method was invoked, where handle is the argument passed to the method, if any. clearTimeout() 方法必须从调用该方法的 WindowTimers 对象的活动超时列表中清除标识为 handle 的条目,其中 handle 是传递给该方法的参数(如果有)。 (If handle does not identify an entry in the list of active timeouts of the WindowTimers object on which the method was invoked, the method does nothing .) (如果句柄未标识调用该方法的 WindowTimers 对象的活动超时列表中的条目,则该方法不执行任何操作。)

Reference 参考

That's because clearTimeout also handles undefined, meaning it has something like a check within the implementation of the function eg那是因为clearTimeout也处理未定义的,这意味着它在函数的实现中有类似的检查,例如

const clearTimeout = (timer) => {
    if (timer) {
        // logic
    }
}

This is probably for better and easier implementation, like you've implemented, so you don't have to worry about such stuff.这可能是为了更好和更容易实现,就像你已经实现的那样,所以你不必担心这些东西。 If it was meant to throw error if timer is null/undefined because it would have some terrible side-effect, they'd probably implement it as如果它打算在计时器为空/未定义时抛出错误,因为它会产生一些可怕的副作用,他们可能会将其实现为

const clearTimeout = (timer) => {
    if (!timer) {
        throw new Error("Timer can not be undefined");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM