淺談js中的防抖(debounce)與節流(throttle)

在實際應用場景中,我們經常遇見高頻調用函數,導致瀏覽器的消耗,但我們可以根據實際需求使用防抖節流函數。

1.防抖

釋義:在限定時間內,只執行一次函數。如果事件再次觸發,則重新計時,計時完畢再執行函數。

 //非立即執行版
function debounce(func, wait) {
    let timeout;
    return function (event) {
        // console.log(event)
        let _this = this
        let _args = arguments
        if (timeout) {
            clearTimeout(timeout)
        }
        timeout = setTimeout(() => {
            func.apply(_this, _args)
        }, wait)
    }
}
 //立即執行版,即首先加載一次
 function debounce2(func, wait) {
     let timeout;
     return function (event) {
         // console.log(event)
         let _this = this
         let _args = arguments
         if (timeout) {
             clearTimeout(timeout)
         }
         console.log(timeout)
         let now = !timeout
         timeout = setTimeout(() => {
             timeout = null
         }, wait)
         if (now) func.apply(_this, _args)
     }
 }
2.節流

釋義:如果持續觸發事件,在一定時間只執行一次函數。

 function throttle(func, wait) {
     let isReady = true
     return function () {
         let _this = this
         let _args = arguments
         if (!isReady) {
             return
         }
         isReady = false
         timeout = setTimeout(() => {
             isReady = true
             func.apply(_this, _args)
         }, wait)
     }
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章