//节流 设置的时间内只能调用一次
//节流函数 写法1 时间差版本
function throttle(method, delay) { let timer, args = arguments, start; return function fn() { let self = this; let now = Date.now(); if(!start){ start = now; } if(timer){ clearTimeout(timer); } if(now - start >= delay){ method.apply(self, args); start = now; }else { timer = setTimeout(function () { console.log(args,'args') fn.apply(self, args); }, delay); } } }
//节流函数 写法2 定时器版本
function throttle(fn,delay) {
var executed = false
return function () {
if(executed) return;
var that = this;
fn.apply(that,...arguments)
executed = true
setTimeout(() => {
executed = false;
}, delay);
}
}
// 防抖函数
function debounce(method,delay){ let _delay = delay || 0; let timer = null; return function(){ let args = arguments; timer && clearTimeout(timer); timer = setTimeout(()=>{ method.apply(this,args) },_delay) } }
这里用的apply和call主要改变this指向。