【问题标题】:I am trying to make a JavaScript function run every 50ms for a certain time interval, but it's not working我试图让 JavaScript 函数在一定的时间间隔内每 50 毫秒运行一次,但它不起作用
【发布时间】: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


    【解决方案1】:

    你需要传递一个回调函数作为第一个参数:

    setInterval(() => clearInterval(myInterval), 2000);
    

    【讨论】:

      猜你喜欢
      • 2017-06-27
      • 2021-08-07
      • 1970-01-01
      • 2018-06-17
      • 2019-02-16
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 2014-05-22
      相关资源
      最近更新 更多