提问人:Dave Moutardier 提问时间:6/15/2022 更新时间:6/15/2022 访问量:218
我正在尝试使 JavaScript 函数在特定时间间隔内每 50 毫秒运行一次,但它不起作用
I am trying to make a JavaScript function run every 50ms for a certain time interval, but it's not working
问:
我的目标是模拟两个骰子的掷骰子,可以选择“动画”掷骰子或仅显示结果。为此,我使用以下脚本
<script>
function roll_dice() {
let _die1 = Math.floor(Math.random() * 6) + 1;
let _die2 = Math.floor(Math.random() * 6) + 1;
let die1_img = `images/${_die1}.png`
let die2_img = `images/${_die2}.png`
document.getElementById("die1").setAttribute("src", die1_img);
document.getElementById("die2").setAttribute("src", die2_img);
}
function animate_dice() {
let myInterval = setInterval(roll_dice, 50);
setTimeout(clearInterval(myInterval),2000);
}
function roll_or_animate() {
if (document.getElementById("should_be_animated").checked == true) {
animate_dice();
} else {
roll_dice();
}
}
</script>
带有调用 roll_or_animate() 的按钮。
未选中should_be_animated没有问题,但是当选中时,骰子只是保持静止,而不是按预期每 50 毫秒“滚动”一次 2 秒。但是如果行
setTimeout(clearInterval(myInterval),2000);
被注释掉,然后骰子每 50 毫秒“掷”一次,尽管没有停止。
我做错了什么?我以为setTimeout会在执行clearInterval之前等待2s,从而停止滚动动画。
答:
1赞
User456
6/15/2022
#1
您需要传递一个回调函数作为第一个参数:
setInterval(() => clearInterval(myInterval), 2000);
1赞
Scott Marcus
6/15/2022
#2
用这句话:
setTimeout(clearInterval(myInterval),2000);
该部分立即执行,无论该调用的返回值是什么,都将在计时器的 2000 毫秒延迟达到后执行。clearInterval(myInterval)
此函数调用的返回值不是第一个参数所需的值。它需要函数引用。因此,若要使该调用等待计时器的时间,需要将该调用包装在函数引用中。setTimeout()
setTimeout(function(){ clearInterval(myInterval) },2000);
评论
== true