# 定时器实现

借助requestAnimationFrame实现,精度更高

# mySetTimeout

function mySetTimeout(callback, delay) {
    let timer, start = Date.now()
    const loop = () => {
        if (start + delay > Date.now()) {
            timer = requestAnimationFrame(loop)
        } else {
            callback(timer)
        }
    }
    loop()
    return timer
}
1
2
3
4
5
6
7
8
9
10
11
12

# mySetInterval

function mySetInterval(callback, delay) {
    let timer, start = Date.now()
    const loop = () => {
        if (start + delay <= Date.now()) {
            callback(timer)
            start = Date.now()
        }
        timer = requestAnimationFrame(loop)
    }
    loop()
    return timer
}
1
2
3
4
5
6
7
8
9
10
11
12