原來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.

發佈了52 篇原創文章 · 獲贊 25 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章