手写场景 | setTimeout实现setInterval

setTimeout() :在指定的毫秒数后调用函数或计算表达式,只执行一次
setInterval() :按照指定的周期(以毫秒计)来调用函数或计算表达式,方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭

手写实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let timer = null;
function myInterval(cb, delay) {
function fn() {
cb();
timer = setTimeout(() => fn(), delay) // 递归调用
};
timer = setTimeout(() => fn(), delay); // 触发递归
}

// 调用
myInterval(() => console.log('正在打印'), 2000);

// 清除定时器
clearTimeout(timer);