【发布时间】:2022-06-15 01:13:56
【问题描述】:
我的目标是模拟掷两个骰子,并可选择“动画”掷骰或仅显示结果。为此,我使用以下脚本
<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 之前等待 2 秒,从而停止滚动动画。
【问题讨论】:
标签: javascript html client-side