JavaScript 防抖(debounce)和节流(throttle)
2021-04-11 21:33
标签:efi demo asc The eset timeout ram cut tle JavaScript 防抖(debounce)和节流(throttle) 标签:efi demo asc The eset timeout ram cut tle 原文地址:https://www.cnblogs.com/leslie1943/p/13358084.html防抖函数
/**
*
* @param {*} fn :callback function
* @param {*} duration :duration time,default wait time 0.8 秒
* @demo in vue methods:
* handleEvent: _debounce(function(){
* do something
* },time)
*/
export const _debounce = (fn, duration = 800) => {
// create timer
let timer = null
return function () {
// reset once call
clearTimeout(timer)
// create a new timer to make sure call after define time
timer = setTimeout(() => {
// execute callbak, the 2nd params is fn‘s arguments
fn.apply(this, arguments)
}, duration)
}
}
节流函数
/**
* @param {*} fn: callback function
* @param {*} duration : duration time,default wait time 1 sec
* @demo in vue methods:
* handleEvent: _throttle(function(){
* do something
* },time)
*/
export const _throttle = (fn, duration = 1000) => {
let canRun = true
return function () {
if (!canRun) return
canRun = false
// execute callbak, the 2nd params is fn‘s arguments
fn.apply(this, arguments)
setTimeout(() => {
canRun = true
}, duration)
}
}
文章标题:JavaScript 防抖(debounce)和节流(throttle)
文章链接:http://soscw.com/index.php/essay/74424.html