1. 程式人生 > 實用技巧 >js 防抖和節流 (學習筆記)

js 防抖和節流 (學習筆記)




/**
 * @desc 函式節流 (牛逼版本)
 * @param func 函式
 * @param wait 延遲執行毫秒數
 * @param type 1 表時間戳版,2 表定時器版
 */
function throttle(func, wait ,type) {
    if(type===1){
        let previous = 0;
    }else if(type===2){
        let timeout;
    }
    return function() {
        let context = this;
        let args 
= arguments; if(type===1){ let now = Date.now(); if (now - previous > wait) { func.apply(context, args); previous = now; } }else if(type===2){ if (!timeout) { timeout = setTimeout(() => { timeout
= null; func.apply(context, args) }, wait) } } } }
/**
 * @desc 函式防抖 (牛逼版本)
 * @param func 函式
 * @param wait 延遲執行毫秒數
 * @param immediate true 表立即執行,false 表非立即執行 
* @param 防抖只會在事件結束後執行一次處理函式 immediate則用來判斷是否直接執行處理函式(func.apply()) 或 延遲執行(setTimeout(()=>{func.apply()},args))
*/ function debounce(func,wait,immediate) { let timeout; return function () { let context = this; let args = arguments; if (timeout) clearTimeout(timeout); if (immediate) { var callNow = !timeout; timeout = setTimeout(() => { timeout = null; }, wait) if (callNow) func.apply(context, args) } else { timeout = setTimeout(function(){ func.apply(context, args) }, wait); } } }
// 節流 (簡易版): 解釋:節流 在事件觸發後會執行N次 間隔對應的時間就會執行一次
例子:設定對應時間為1 則事件觸發後每一秒執行一次處理函式
var throttle = function(func, delay) { var timer = nullvar startTime = Date.now()//獲取第一次當前時間戳
return function() { var curTime = Date.now() // 獲取執行時的時間戳 var remaining = delay - (curTime - startTime)// 獲取時間差 並獲取是否到達觸發的間隔時間 var context = this; var args = arguments; clearTimeout(timer); if (remaining <= 0) {// 判斷是否到達觸發時間 (設定的觸發間隔時間)小於(當前觸發於上次間隔時間) 當remaining小於0時 觸發處理函式 並重新定義第一次時間戳 func.apply(context, args); startTime = Date.now(); } else { timer = setTimeout(func, remaining)// 註冊定時器 } } } function handle() { console.log(Math.random()); } window.addEventListener('scroll', throttle(handle, 1000))
// 防抖(簡易版) 解釋:事件觸發結束後才會執行一次處理函式 觸發跟觸發時不會進入處理函式
function antiShake(fn, delay = 300) {    
    var timer = null
   return function () {
        if (timer !== null) {
          clearTimeout(timer)
        }
     timer = setTimeout(fn, delay)
    }
}
// 處理函式
function fun() {    
  console.log('0')
}
// 滾動事件
window.addEventListener('scroll',antiShake(fun, 1000))

例子:

防抖使用場景 監聽input事件輸入事件 觸發請求 不能每次輸入都請求 浪費資源並會造成卡頓 這個時候防抖最合適

節流使用場景 監聽滾動事件 選擇位址列 滾動到對應的城市 選中對應城市的字母 不能等待事件結束再去觸發處理函式 則使用節流 短時間去觸發處理函式 這個時候節流最合適