原来clearInterval和 clearTimeout可以互用

setInterval和setTimeout返回的是一个整数ID。从技术上来说clearInterval和clearTimeout是可以互用的,如下所示。不过这样做会造成语义上的歧义,因此并不建议。

var timer = setInterval(function() {
    console.log('hello world');
}, 1000);
// clearInterval(timer);
clearTimeout(timer); // 这样也可以

MDN 关于setInterval的解释

It may be helpful to be aware that setInterval() and setTimeout() share the same pool of IDs, and that clearInterval() and clearTimeout() can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code.


版权声明:本文为Marshall001原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。