防抖:你狂点按钮也没有,等你冷静下来事件才会触发。
节流:游戏里面的技能冷却功能。app
//防抖例子1 function debounce(fn,delay=200){this
let timer = null;游戏
return function(){事件
if(timer) clearTimeout(timer);it
timer = setTimeout(()=>{io
fn.apply(this,arguments);function
timer = null; },delay);定时器
}im
}时间戳
}
//例子2
function debounce(func, wait) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args) }, wait);
}
}
}
节流
//时间戳版
function throttle(func, wait) {
let previous = 0;
return function() {
let now = Date.now();
let context = this;
let args = arguments;
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}
}
//定时器版
function throttle(func, wait) {
let timeout;
return function() {
let context = this;
let args = arguments;
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args) }, wait)
}
}
}