JavaScript函数防抖(debounce)与函数节流(throttle),这两个词听起来高端大气上档次,但是其实在平时做项目的时候,我们都可能不经意用到这中处理方式(很有必要,降低性能消耗),例如mousemove
(移动),scroll
(滚动),drag
(拖拽),resize
(窗口变化)等事件,触发过程中都是需要大量的计算,这时候会很消耗内存,所以需要一点手段来降低性能消耗。
用两种方式解释吧:
专业解释
函数防抖:在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。
函数节流:规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次生效。
通俗点讲
函数防抖:
在触发一个事件(或者ajax请求)的时候,为了防止有些用户乱点一通,你想防止他多次触发(请求多次),这时候就需要让这个事件(或者ajax请求)触发一次之后
启动定时器
,禁止该事件在一段时间内再次被触发停止定时器
,这差不多就是我们理解的函数防抖了
函数节流:
在连续触发事件的时候,达到每隔一段时间触发一次,这样就不会频繁的触发,也不像函数防抖一样最后一次触发,时间较长的时候是间隔执行,而不是等滚动停止之后再执行。比如实时搜索
2种js处理方式使用场景
函数防抖例子: 连续触发,清除之前定时器,运行最后停止触发的定时器(一次)
- 下拉滚动
- 判断输入内容
- …
1:下拉滚动
<div class="d1"></div>
var sHeight,
bottom,
time,
body = document.getElementsByTagName('body')[0],
offsetHeight = document.documentElement.offsetHeight,
clientHeight = document.documentElement.clientHeight
window.onscroll = function (e){
clearTimeout(time) // 当再次触发的时候就清除掉之前还没运行的定时器
sHeight = document.documentElement.scrollTop
bottom = offsetHeight - clientHeight - sHeight
time = setTimeout(function() { // 第一次触发的时候 启动定时器
console.log(sHeight)
if (bottom < 200) {
console.log('触发')
}
}, 500);
}
2:验证输入
<input type="text" id='d1'>
var time
var d1 = document.getElementById('d1')
d1.oninput = function (e){
clearTimeout(time)
time = setTimeout(function () {
console.log(e.target.value)
}, 500);
}
函数节流例子: 连续触发,根据间隔判断‘必执行’,
- 下拉滚动
- 搜索框输入实时触发搜索
- window 窗口resize
- …
1:下拉滚动
var timeout
window.onscroll = throttle(test,1000,500)
function throttle(fun, interval, delay) {
var oldTime = new Date(); // 获取当前时间
return function() {
var salf = this,
argum = arguments,
newTime = new Date();
clearTimeout(timeout);
if (newTime - oldTime >= 1000) { // 设置时间间隔1s
fun.apply(salf, argum); // 超过时间间隔1s 重置当前时间
oldTime = newTime;
} else { // 没超过时间间隔1s 重新设定定时器
timeout = setTimeout(fun, 500);
}
}
}
function test() {
console.log('触发')
}