问题描述
我正在使用 JavaScript 和 HTML 在我的网页上制作贪吃蛇游戏。在这个游戏中,我想在固定的时间间隔后调用一个函数。此函数将更新并打印蛇的位置。
为此,我使用 setTimeOut(my_function,time)。
我的代码是这样的
function my_function(){
// update values
// display snake
setTimeOut(my_function,time)
}
我的问题是 - 上面的代码是否会像递归函数一样在函数堆栈上创建大量函数调用。我想会的。
以下是我认为可以优化它的方法。
function empty_function{
}
while(true){
//update values
//display snake
setTimeOut(empty_function,time)
}
解决方法
您可以通过 setInterval
更轻松地实现此目的。这是一个示例;
setTimeout(() => {console.log('this will get printed only once after 1000 ms')},1000);
setInterval(() => {console.log('this will get printed after every 1000 ms')},1000);
setInterval
在给定的时间间隔后一次又一次地运行一个函数。
如果你想停止 setInterval
函数,你可以这样做;
let myinterval = setInterval(() => {console.log('Print this again and again after 1000 ms')},1000);
// Down here i am clearing the 'myInterval' interval using the 'clearInterval' function.
const clear = () => {
console.log('printing stopped');
clearInterval(myinterval);
}
document.getElementById('stop').addEventListener('click',clear);
<button id='stop'>Stop printing</button>