节流
如果持续触发事件,每隔一段事件,只执行一次事件
应用场景
- DOM元素的拖拽功能实现
- 射击游戏
- 计算鼠标移动的距离
- 监听 scroll 滚动事件
通过时间戳 和 定时器 的结合来实现 执行第一次的运算和最后一次的运算,
function throttle(func, time, options) {
let context, args, timeout;
let old = 0;
if(!options) options ={}
return function () {
context = this;
args = arguments;
let now = new Date().valueOf();
if(timeout){
clearTimeout(timeout)
timeout = null
}
if(options.leading === false && !old){
old = now
}
// 通过时间差的执行
if (now - old > time) {
func.apply(context, args);
old = now
}
if(!timeout && options.throttle !== false){
// 定时器
timeout = setTimeout(()=>{
old = new Date().valueOf()
timeout = null
func.apply(context,args)
},time)
}
};
}
let count = 0;
function fn(e) {
console.log(e);
console.log(this);
btn.textContent = count++;
return "我要的结果";
}
let doSome = throttle(fn, 2000,{
leading:false,
throttle:true
});
btn.onmousemove = doSome;