节流:规定时间内只能执行一次。
if (!time) {
console.log('诶,不让你执行');
return false;
}
time = false;
setTimeout(() => {
console.log('诶,我执行了');
time = true;
}, 3000)
防抖:规定时间如果有新的触发,从新计时。
let timeNum = null;
function bb() {
if (timeNum !== null) {
console.log('我没有执行', timeNum);
clearTimeout(timeNum);
}
timeNum = setTimeout(() => {
console.log('诶,我执行了');
timeNum = null;
}, 3000)
}
更新版本:这个用的是 call 方法,传递参数遵守 call 方法传递参数规则
let throttle = function () {
var timer = null;
return function (func, delay) {
const Athis = this;
const args = [...arguments].splice(2);
if (!timer) {
timer = setTimeout(function () {
console.log(args);
result = func.call(Athis, ...args);
timer = null;
}, delay);
}
}
}
let throttle1 = throttle();
function print(str) {
console.log('诶,我执行了', str);
}
<button onclick="throttle1(print, 3000,'你好啊')">点击</button>
这个是先执行一次:
private time = true;
private timeNum = 0;
private visibleChange(id: number) {
if (!this.time) {
clearTimeout(this.timeNum);
this.timeNum = setTimeout(() => {
this.time = !this.time;
}, 10);
return false;
}
this.visible = true;
this.visibleIndex = id;
this.time = false;
}