setInterval 和 setTimeout 定時器

前端定時器 setInterval 和 setTimeout

setInterval 循環執行

循環執行就是設置一個時間間隔,每過一段時間都會執行一次這個方法,直到這個定時器被銷燬掉。前端

用法是setInterval(「方法名或方法」,「延時」), 第一個參數爲方法名或者方法,注意爲方法名的時候不要加括號,第二個參數爲時間間隔(毫秒)。vue

設置循環執行
this.timer = setInterval(this.updataDevice, 5000)
// 第一個參數:this.updataDevice 是ts中的方法,只寫方法名不寫括號。
// 第二個參數:5000 表示延時,毫秒,5000毫秒=5秒,即執行完本次後,隔5秒再次執行
銷燬定時器

案例是vue寫的,用vue舉例:函數

beforeDestroy() {  // 組件銷燬前執行
      clearInterval(this.timer)  // 清除定時器
      this.timer = null  // 定時器的變量賦值null
    },

順便例一下vue的生命週期函數:this

beforeCreate: function () {
            console.group('beforeCreate 建立前狀態===============》');
        },
        created: function () {
            console.group('created 建立完畢狀態===============》');
        },
        beforeMount: function () {
            console.group('beforeMount 掛載前狀態===============》');//已被初始化
        },
        mounted: function () {
            console.group('mounted 掛載結束狀態===============》');
        },
        beforeUpdate: function () {
            alert("更新前狀態");
            console.group('beforeUpdate 更新前狀態===============》'); //這裏指的是頁面渲染新數據以前
            alert("更新前狀態2");
        },
        updated: function () {
            console.group('updated 更新完成狀態===============》');
        },
        beforeDestroy: function () {
            console.group('beforeDestroy 銷燬前狀態===============》');
        },
        destroyed: function () {
            console.group('destroyed 銷燬完成狀態===============》');
        }

setTimeout 定時執行

定時執行setTimeout是設置一個時間,等待時間到達的時候只執行一次,可是執行完之後定時器還在,只是沒有運行。code

用法是 setTimeout(「方法名或方法」, 「延時」); 第一個參數爲方法名或者方法,注意爲方法名的時候不要加括號,第二個參數爲時間間隔。生命週期

設置定時執行
setTimeout(() => {
          this.showMarker()  // 執行的方法
        }, 1000)  // 時間 1000毫秒 = 1秒
相關文章
相關標籤/搜索