Home > OS >  I am trying to make a JavaScript function run every 50ms for a certain time interval, but it's
I am trying to make a JavaScript function run every 50ms for a certain time interval, but it's

Time:06-15

My goal is to simulate the roll of two dice, with an option to "animate" the roll or merely show the result. For this, I'm using the following script

<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>

with a button that calls roll_or_animate().

There is no issue when should_be_animated is unchecked, but when it is checked, the dice merely stay still rather than "rolling" every 50ms for 2s as intended. But if the line

setTimeout(clearInterval(myInterval),2000);

is commented out, then the dice do "roll" every 50ms, albeit without stopping.

What am I doing wrong? I thought that setTimeout would wait 2s before executing clearInterval, thus stopping the rolling animation.

CodePudding user response:

You need to pass a callback function as the first parameter:

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

CodePudding user response:

With this line:

 setTimeout(clearInterval(myInterval),2000);

The clearInterval(myInterval) portion is executing immediately and whatever the return value from that call is is what will be executed after the timer's 2000 ms delay is hit.

The return value from this function call is not what the first argument of setTimeout() requires. It requires a function reference. So to make that call wait for the timer's time, you need to wrap that call in a function reference.

setTimeout(function(){ clearInterval(myInterval) },2000);
  • Related