首页 > 解决方案 > 我怎样才能使结果一致?SetInterval 无法正常工作

问题描述

我正在用 JavaScript 开发一个游戏,我试图让一个点移动,但是一旦它被移动了,它就不会保持相同的值。我试图将 setInerval 设置为 var 然后清除它,但它没有用。

请让我知道我做错了什么,我该如何解决?

<!DOCTYPE html>
    <html lang="en">
        <head>
        <script>
    let x = 0;
    let isKey = 0;

function goingUp() {
    x -= 1;
}

function goingDown() {
    x += 1;
}

document.addEventListener('keydown', (event) => {

    if (event.key === 'ArrowDown' && isKey !== -1) {
        setInterval(goingDown, 50);
        isKey -= 1
    } else if (event.key === 'ArrowUp' && isKey !== 1) {
        setInterval(goingUp, 50);
        isKey += 1
    }})


let lastFrameTimeMs = 0, // The last time the loop was run
    maxFPS = 60; // The maximum FPS we want to allow

function startGame(timestamp) {
    // Throttle the frame rate.    
    if (timestamp < lastFrameTimeMs + (500 / maxFPS)) {
        requestAnimationFrame(startGame);
        return;
    }

    lastFrameTimeMs = timestamp;  
    console.log(x)

    requestAnimationFrame(startGame);
}

requestAnimationFrame(startGame);

        </script>
        </head>
    </html>

标签: javascriptsetintervalkeyevent

解决方案


推荐阅读