模拟实现setTimeout
const timerList = new Set();
function setTimeout(fn,delay){
const last = new Date().getTime();
function start(){
requestAnimationFrame(()=>{
if(!timerList.has(id)) return;
const now = new Date().getTime();
if(now - last >= delay){
fn();
timerList.delete(id);
return
}
start();
})
}
start();
const id = Symbol();
timerList.add(id);
return id
}
function clearTimeout(id){
timerList.delete(id);
}
模拟实现setInterval
const timerList = new Set();
function setInterval(fn,delay){
let last = new Date().getTime();
function start(){
requestAnimationFrame(()=>{
if(!timerList.has(id)) return;
const now = new Date().getTime();
if(now - last >= delay){
fn();
last = now;
}
start();
})
}
start();
const id = Symbol();
timerList.add(id);
return id
}
function clearInterval(id){
timerList.delete(id);
}