原来clearInterval和 clearTimeout可以互用

来源:互联网 发布:计算机编程有什么种类 编辑:程序博客网 时间:2024/06/03 08:45

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.

阅读全文
1 0