首页 > 解决方案 > execute a code after every 1/24 sec not working

问题描述

I am trying to run a piece of code in requestFrameAnimation. The code should run after every 1/24 sec. I am using javascript date() library to get current time. Here is my code

animate = () => {

    let canvas = document.getElementById('timeline-canvas')
    let ctx =  canvas.getContext('2d')



    let currentTime = new Date().getTime() / 1000;


    if (currentTime >= lastTime + (1000/24))  {
        console.log(lastTime)
        // 1/24 second has passed, run some code here
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.beginPath()
        ctx.strokeStyle = 'blue'
        ctx.lineWidth = 5
        ctx.moveTo(x_pos, 0)
        ctx.lineTo(x_pos, canvas.height)
        ctx.stroke()
        ctx.save()
    }
    x_pos += 1
    lastTime = currentTime
    requestAnimationFrame(this.animate);

}

The if loop only runs once. I expect it to run every 1/24 sec. What am I doing wrong?

标签: javascript

解决方案


你的这部分应该在 if 语句里面

lastTime = currentTime

所以它看起来像这样

if (currentTime >= lastTime + (1000/24))  {
    console.log(lastTime)
    // 1/24 second has passed, run some code here
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath()
    ctx.strokeStyle = 'blue'
    ctx.lineWidth = 5
    ctx.moveTo(x_pos, 0)
    ctx.lineTo(x_pos, canvas.height)
    ctx.stroke()
    ctx.save()
    lastTime = currentTime
}

如果您将此语句放在 if 块之外,您的最后一次将每秒更新一次。如果有帮助,标记为已解决


推荐阅读