使用setTimeout实现setInterval,支持清除定时器。
function mySetInterval(func, interval) {
let timeoutId = setTimeout(function() {
func();
mySetInterval(func, interval);
}, interval);
return timeoutId; // 返回定时器ID
}
function myClearInterval(timeoutId) {
clearTimeout(timeoutId); // 使用定时器ID清除定时器
}
const intervalId = mySetInterval(function() {
console.log('this will be logged every 2 seconds');
}, 2000);
// 在6秒后停止定时器
setTimeout(function() {
myClearInterval(intervalId);
console.log('Timer cleared');
}, 6000);