Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

339
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda