js 实现after


实现 after 方法
在 JavaScript 中,after 方法通常用于在指定次数后执行某个函数。以下是几种实现方式:
使用闭包实现
function after(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
}
// 示例用法
const callAfter2 = after(2, function() {
console.log('Called after 2 times');
});
callAfter2(); // 不执行
callAfter2(); // 输出: Called after 2 times
使用 ES6 类实现
class After {
constructor(times, fn) {
this.times = times;
this.fn = fn;
}
call() {
if (--this.times <= 0) {
this.fn();
}
}
}
// 示例用法
const after = new After(3, () => console.log('Called after 3 times'));
after.call(); // 不执行
after.call(); // 不执行
after.call(); // 输出: Called after 3 times
使用 Promise 实现
function after(times) {
let count = 0;
return new Promise((resolve) => {
const interval = setInterval(() => {
count++;
if (count >= times) {
clearInterval(interval);
resolve();
}
}, 1000);
});
}
// 示例用法
after(3).then(() => console.log('Resolved after 3 seconds'));
使用 async/await 实现
async function after(times, callback) {
let count = 0;
while (count < times) {
await new Promise(resolve => setTimeout(resolve, 1000));
count++;
}
callback();
}
// 示例用法
after(2, () => console.log('Called after 2 seconds'));
这些实现方式可以根据具体需求选择使用。闭包方式适合简单的次数控制,类实现提供了更好的封装,Promise 和 async/await 适合处理异步场景。





