兩種方法:1、用clearTimeout()清除setTimeout定時器,語法“clearTimeout(定時器回傳值)”;2、clearInterval()清除setInterval定時器,語法“clearInterval(傳回值)” 。
本教學操作環境:windows7系統、ECMAScript 6版、Dell G3電腦。
JS的兩個計時器
#window.setTimeout([function],[interval])
##設定一個計時器,並且設定了一個等待的時間,當到達時間後,執行對應的方法,當方法執行完成計時器停止。
計時器傳回值JS中的計時器是有回傳值的,回傳值是一個數字,代表目前是第幾個定時器。
var timer1=window.setTimeout(function(){},1000); //timer1->1 当前是第一个定时器 var timer2=window.setTimeout(function(){},1000); //timer2->2` 当前是第二个定时器 var timer3=window.setTimeout(function(){},1000); //timer3->3 当前是第三个定时器
setInterval物件或setTimeout對象,這兩個定時器物件只會隨著視窗物件的銷毀才從堆疊空間回收。無法透過更改變數的指標指向null的方式通知垃圾回收機自動回收。如果打算在視窗物件關閉之前銷毀視窗物件的堆疊記憶體中的setInterval物件只能透過clearInterval銷毀它
clearTimeout(id_of_settimeout)
var myVar = setTimeout(function(){ alert("Hello"); }, 3000); clearTimeout(myVar);
##是否需要及時清理setTimeOut
#function testTimeout () {
console.log('1111')
console.log(setTimeout(testTimeout, 3000));
}
所以我們應該在每次 setTimeout 之前呼叫 clearTimeout,防止不斷建立setTimeout物件而未被GC回收。
var timeHandle = null; function testTimeout () { if (timeHandle) { // 调用之前,先清理,防止一直生成对象 // ps. setInterval 定时器也应该按这种模式处理 clearTimeout(timeHandle); timeHandle = null; } console.log('1111'); console.log(timeHandle = setTimeout(testTimeout, 3000)); }
#定義: 可取消/停止由 setInterval() 函數設定的定時執行操作。
注意: 要使用clearInterval() 方法, 在建立執行定時操作時要使用全域變數:
var myVar = setInterval(function(){ myTimer() }, 1000); clearInterval(myVar);
是否需要及時清理setInterval#function testInterval () {
console.log('1111')
console.log(setInterval(testInterval, 3000));
}
var timeHandle = null; function testInterval () { if (timeHandle) { // 调用之前,先清理,防止一直生成对象 clearInterval(timeHandle); timeHandle = null; } console.log('1111'); console.log(timeHandle = setInterval(testInterval, 3000)); }
//实现的方法挺简单的 ,如下代码 //参数: 毫秒 需要执行的方法 function console1() { console.log(111); if(timer){ clearTimeout(timer); } timer = setTimeout(function(){ console1(); }, 3000); } console1()
以上是es6怎麼清除定時器的詳細內容。更多資訊請關注PHP中文網其他相關文章!