函数防抖和节流

函数防抖:将几次操作合并为一次操作进行。原理是维护一个计时器,规定在delay时间后触发函数,但是在delay时间内再次触发的话,就会取消之前的计时器而重新设置。这样一来,只有最后一次操作能被触发。

函数节流:使得一定时间内只触发一次函数。原理是通过判断是否到达一定时间来触发函数。

相同之处:解决频繁触发某个事件的情况造成的性能消耗。

区别:函数节流不管事件触发有多频繁,都会保证在规定时间内一定会执行一次真正的事件处理函数,而函数防抖只是在最后一次事件后才触发一次函数。

防抖适用场景:例如,在进行搜索的时候,当用户停止输入后调用方法,节约请求资源

节流适用场景:例如,在页面的无限加载场景下,我们需要用户在滚动页面时,每隔一段时间发一次 Ajax 请求,而不是在用户停下滚动页面操作时才去请求数据。这样的场景,就适合用节流技术来实现。


const inp = document.getElementById('input') function debounce(fun,delay){ let timer ; return function(args){ const that = this clearTimeout(timer) timer = setTimeout(function(){ fun.call(that,args) },delay) } } const debounceInput = debounce(input,5000) inp.addEventListener("keyup",function(e){ debounceInput(e.target.value) })
// 节流
function
input(value) { console.log(`输入的内容${value}`) } const inp= document.getElementById('input') function throttle(fun,delay){ let last,timer; return function(args){ const that = this const now = +new Date() if(last && now < last + delay){ clearTimeout(timer) timer = setTimeout(function(){ fun.call(that,args) },delay) }else{ last = now fun.call(that,args) } } } const throttleInput = throttle(input,1000) inp.addEventListener("keyup",function(e){ throttleInput(e.target.value) })

原文参考:https://www.cnblogs.com/smallpen/p/10289050.html

原文地址:https://www.cnblogs.com/linjiu0505/p/11867969.html