Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

234
Visualizações
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 Respostas
Responde à pergunta

0

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

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

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda