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

343
Visualizações
Timer: setTimeout and function call
function tick() {
    seconds_lapsed++; // Break point.
}

function countdown() {   

    while(!stopped || !is_paused()){
        setTimeout(tick, 1000); // 1 second.
        show_counter();
    }
}

Could you tell me why the interpreter doesn't stop at the breakpoint? The while loop works, hava a look at the screenshot.

enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The while loop is a "busy" loop, i.e. it keeps the JavaScript engine busy, so it will not process anything that is waiting in one of its event/job queues. This means that the user interface does not get updated, no input can be processed, and events produced by setTimeout are not consumed. In this example, tick can only get executed if the currently running code finishes. So the while loop must end first.

You should let tick execute, and only then check the condition:

var stopped = true;
var seconds_lapsed = 0;

document.querySelector("button").addEventListener("click", function() {
    stopped = !stopped;
    seconds_lapsed = 0;
    this.textContent = stopped ? "Start" : "Stop";
    if (!stopped) countdown();
});

function show_counter() {
    document.querySelector("span").textContent = seconds_lapsed;
}

function is_paused() {
    return document.querySelector("input").checked;
}

function tick() {
    seconds_lapsed++;
}

function countdown() {   
    show_counter();
    setTimeout(function () {
        if (stopped) return; // stop the loop
        if (!is_paused()) tick();
        countdown(); // <--- this is the "loop"
    }, 1000);
}
Seconds elapsed: <span>0</span><br>
<input type="checkbox">Paused<br>
<button>Start</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

the following example might help you accomplish what you are after. Distinguish between setInterval() and setTimeout()

Basically the docs say:

setTimeout executes a function or specified piece of code once the timer expires.

setInterval repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

So if you use setInterval you don't need a while loop inside because it is already called "repeatedly"

var counter = $('#counter');

var stopped = false;
var seconds_lapsed=0;
var myInterval;

function tick() {
    if(stopped) {
        clearInterval(myInterval);
        show_counter('FINISHED');
        return;
    }
    show_counter(seconds_lapsed++);
}

function show_counter(message){ 
    counter.html(message);
}

function countdown() {   
    myInterval = setInterval(tick, 1000);
}

function endCountdown(timeout) {
    let timeoutId = setTimeout(function(){
        stopped = true;
        clearTimeout(timeoutId)
    }, timeout);
}

countdown(); // start the countdown

endCountdown(5000); // ends the countdown after 5000 ms => 5sec
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="counter">counter</div>

about 4 years ago · Juan Pablo Isaza 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