防抖和节流
作者:互联网
基本概念
防抖 | 节流 |
---|---|
在频繁的触发事件时,并在一定时间内没有触发事件,事件函数才会调用一次 | 在频繁的触发事件时,保证在一定时内调用一次事件函数 |
实现
- 防抖
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('发请求了') }
标签:function,防抖,null,节流,let,now,timerId,fn 来源: https://www.cnblogs.com/aloneer/p/15087711.html