s008-手写函数节流★★
//手写函数节流,
function throttle(fn,delay = 100) {
let timer = null;
return function() {
let ctx = this;
if(timer) {
return
}
timer = setTimeout(() => {
fn.apply(ctx,arguments)
timer = null;
},delay)
}
}
函数节流使用的挺多场景就是,拖拽
div1.addEventListener('drag',throttle(function(e) {
console.log(e.offsetX)
},200))
function throttle(fn,delay) {
let timer = null;
let start = Date.now();
return function() {
let nowTime = Date.now();
let left = delay - (nowTime - start);
let context = this;
let args = arguments;
clearTimeout(timer);
if(left <= 0) {
fn.apply(context,agrs)
start = Date.now();
} else {
timer = setTimeout(fn,left)
}
}
}
function throttle(fn, delay){
let that = this
let lastTime = 0
return function() {
let nowTime = new Date().getTime()
if(nowTime - lastTime < delay) return // 两次时间间隔比设定的delay则return
let arg = arguments // 此处为fn函数的参数
fn.apply(that, arg)
lastTime = nowTime // 把当前时间赋值给lastTime
}
}
function test(a,b) {
console.log(a,b)
}
let throttleTest = throttle(test, 1000)
window.onscroll = function(e) {
throttleTest(1,2)
}