Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

229
Views
I am trying to make a JavaScript function run every 50ms for a certain time interval, but it's not working

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.

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

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

setInterval(() => clearInterval(myInterval), 2000);
about 4 years ago · Santiago Gelvez Report

0

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);
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!