定義
- setTimeout():延時任務。在指定的毫秒數后調用函數或計算表達式,
- setInterval():定時任務。在每隔指定的毫秒數循環調用函數或表達式,直到clearInterval把它清除。
- setTimeout()只執行一次,而setInterval可以多次調用。
栗子
- setInterval() 定時器
this.timer = setInterval( ()=> {
console.log( "每隔1秒鍾我就會顯示一次" )
},1000);
- 1
- 2
- 3
clearInterval(this.timer) //清除定時器
- 1
- setTimeout() 延時器
var timer = setTimeout( function() {
alert("hellow world!");
},1000);
- 1
- 2
- 3
clearTimeout( timer ); //clearTimeout(ID)來取消 未執行 的超時調用
- 1
輪詢
輪詢就是不斷地去調用同一個接口。當離開這個界面時,就停止對這個接口的不斷調用。
mounted(){
// 輪循
this.timer = window.setInterval(() => {
setTimeout(() => {
this.getList() //調用接口的方法
console.log(1111111111)
}, 1)
}, 3000);
},
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
vue 是單頁面應用,路由切換后,定時器並不會自動關閉,需要手動清除,當頁面被銷毀時,清除定時器即可。
destroyed(){
clearInterval(this.timer)
},
- 1
- 2
- 3