Draknek直面會:多款益智獨立遊戲登陸Switch
阿新 • • 發佈:2021-07-28
基本概念
防抖 | 節流 |
---|---|
在頻繁的觸發事件時,並在一定時間內沒有觸發事件,事件函式才會呼叫一次 | 在頻繁的觸發事件時,保證在一定時內呼叫一次事件函式 |
實現
- 防抖
function dbbounce(fn, await = 1000) { let timerId = null let context = this let args = arguments function shake() { if (timerId) { clearTimeout(timerId) timerId = null } timerId = setTimeout(function() { fn.apply(context, args) }, await) } return shake }
// 第一次立即執行 function dbbounce(fn, fnawait = 200) { let timerId = null function shake() { if (timerId) clearTimeout(timerId) const callNow = !timerId timerId = setTimeout(() => { timerId = null }, fnawait) if (callNow) fn.apply(this, arguments) } return shake }
- 節流
// 時間戳寫法,第一次立即執行 function throttle(fn, interval) { let last = 0; return function() { let now = Date.now(); if (now - last >= interval) { last = now fn.apply(this, arguments) } } }
// 定時器寫法,第一次延遲執行 function throttle(fn, interval) { let timer = null; return function () { let context = this; let args = arguments; if (!timer) { timer = setTimeout(function() { fn.apply(context, args) timer = null }, interval) } } }
// 第三種寫法, function throttle(fn, delay) { let timer = null; let startTime = Date.now(); return function() { let curTime = Date.now(); let remainning = delay - (curTime - startTime); let context = this; let args = arguments; clearTimeout(timer); if (remainning <= 0) { fn.apply(context, args); startTime = Date.now(); } else { timer = setTimeout(fn, remainning) } } }
在vue中封裝使用
- 定義
<!-- 變數要定義在外面,函式內無效 --> let timerId = null export function dbbounce(fn, fnawait = 200) { function shake() { if (timerId) clearTimeout(timerId) const callNow = !timerId timerId = setTimeout(() => { timerId = null }, fnawait) if (callNow) fn.apply(this, arguments) } return shake } let lastCall = null export function throtting(fn, time = 1000) { function func() { const now = new Date().getTime() if (now - lastCall < time && lastCall) return lastCall = now fn.apply(this, arguments) } return func }
- 使用
import { dbbounce, throtting } from '@/utils/index' // 防抖事件 dbbounceClick() { dbbounce(this.requstss, 1000)() }, // 節流事件 throttingClick() { throtting(this.requstss)() }, // 網路請求 requstss() { console.log('發請求了') }