[JavaScript] 纯文本查看 复制代码
//例子1
function debounce(fn,delay=200){
let timer = null;
return function(){
if(timer) clearTimeout(timer);
timer = setTimeout(()=>{
fn.apply(this,arguments);
timer = null;
},delay);
}
}
//例子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);
}
}
[JavaScript] 纯文本查看 复制代码
//时间戳版
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;
}
}
}
throttle(count,1000);
//定时器版
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)
}
}
}