防抖和节流
// 防抖
export const debounce= (func, wait) => {
var timeout;
return function () {
var context = this;
var args = arguments;
clearTimeout(timeout)
timeout = setTimeout(function(){
func.apply(context, args)
}, wait);
}
};
// 节流
export const throttle = (fn, wait) => {
let canRun = true; // 通过闭包保存一个标记
return function () {
if (!canRun) return; // 在函数开头判断标记是否为true,不为true则return
canRun = false; // 立即设置为false
setTimeout(() => { // 将外部传入的函数的执行放在setTimeout中
fn.apply(this, arguments);
// 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。当定时器没有执行的时候标记永远是false,在开头被return掉
canRun = true;
}, wait);
};
}
let debounce= (func, wait) => {
var timeout;
return function () {
var context = this;
var args = arguments;
console.log(args);
clearTimeout(timeout)
timeout = setTimeout(function(){
func.apply(context, args)
}, wait);
}
};
let a = debounce(function(d){console.log(d)},500)
let b = 1;
a(b)
setTimeout(function(){
b=20;
a(b)
}, 100);
let throttle = (fn, wait) => {
let canRun = true; // 通过闭包保存一个标记
return function () {
if (!canRun) return; // 在函数开头判断标记是否为true,不为true则return
canRun = false; // 立即设置为false
setTimeout(() => { // 将外部传入的函数的执行放在setTimeout中
fn.apply(this, arguments);
// 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。当定时器没有执行的时候标记永远是false,在开头被return掉
canRun = true;
}, wait);
};
}
let a = throttle(function(d){console.log(d)},500)
let b = 1;
a(b)
setTimeout(function(){
b=20;
a(b)
}, 100);

浙公网安备 33010602011771号