setTimeout 实现递归实现
const mySetInterval = (cb, time) => {
const fn = () => {
cb();
setTimeout(() => {
fn();
}, time);
}
fn();
}
mySetInterval(() => {
console.log(new Date())
}, 1000)
非递归实现
const setInterval1 = (func, interval) => {
let startTime = Date.now();
const config = { shouldStop: false };
while (!config.shouldStop) {
if (Date.now() - startTime >= interval) {
func();
startTime = Date.now();
}
}
return config;
}
const myClearInterval = config => { config.shouldStop = true; }
网友评论