blog
blog copied to clipboard
去抖 | 节流
节流
函数节流能使得连续的函数执行,变为 固定时间段 间断地执行。 (通常情况下此函数为 DOM 事件的回调函数)
function throttle(method, time, context) {
if (method.tId){return}
method.call(context)
method.tId = true
setTimeout(function() {
method.tId = false
}, time);
}
xxx
throttle = function (fn, time){
let cd = false
return function (){
if (cd){return}
fn.call()
cd = true
setTimeout(() => {cd = false},time)
}
}
fn = function (){
console.log('a')
}
for (var i=0; i<100; i++){
throttle(fn, 10000)()
}
去抖
函数去抖就是对于一定时间段的连续的函数调用,只让其执行一次。 用户输入搜索、滚动加载
function debounce(method, time, context) {
clearTimeout(method.tId);
method.tId = setTimeout(function() {
method.call(context);
}, time);
}
xxx
function debounce(fn, time, context) {
let timer = undefined
return function (){
if (timer !== undefined){
window.clearTimeout(timer)
}
timer = setTimeout( () => {
fn.call()
}, time)
}
}
function print() {
console.log('hello world',);
}
window.onscroll = function() {
debounce(print, 1000);
};