javascript - 我怎样才能使结果一致?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>
解决方案
推荐阅读
- android - 如何从 getter 写入片段中的 listView?
- kubernetes - 需要在不删除已经运行的 pod 的情况下升级 helm chart
- c# - 安装应用后指定的元数据路径无效
- php - 如何使用 PHP file_get_contents 重写 .txt 文件循环中的 1 个特定行
- reactjs - reactjs Route Not Found 请求的 URL
- three.js - 有没有可能在threejs中使用GIF动画?
- javascript - @babel/plugin-transform-modules-amd 的行为不符合预期
- gremlin - 使用带有 unname 和密码的 gremlin-python 连接到远程 gremlin-server
- c# - 是否可以指定条件输出绑定?
- php - 使用php在文本框中显示sql变量