如何使结果一致? SetInterval无法正常工作

问题描述 投票:0回答:1

我正在使用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>
javascript setinterval keyevent
1个回答
0
投票

您是否尝试过setTimeout而不是setInterval

© www.soinside.com 2019 - 2024. All rights reserved.