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

167
Vistas
How do I perform a simple toggle operation in JavaScript with the help of setInterval()?

This is what my code looks like:

var fnInterval = setInterval(function() {
  let b = true
  if (b) {
    console.log("hi")
  } else {
    console.log("bye")
  }
  b = !b
}, 1000);

clearTimeout(fnInterval, 10000)

I am a newbie to JavaScript and my aim here is to console log a message every 1 second for a total duration of 10 seconds, but during each interval I want my message to toggle its value between "hi" and "bye" . How can I do it? (as of now it displays the value for the default boolean and doesn't change later)

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Move the flag variable out of the function:

let b = true;

const fnInterval = setInterval(function() {
    if (b) {
        console.log("hi");
    } else {
        console.log("bye");
    }
    b = !b
}, 1000);

To stop the timer after 10000 milliseconds, wrap the call to clearInterval in a setTimeout:

setTimeout(() => clearInterval(fnInterval), 10000);

Meanwhile, note that the return value of setInterval is not a function but a number, so it may be misleading to call it fnInterval.

about 4 years ago · Juan Pablo Isaza Denunciar

0

First of all, declare let b = true outside of the callback function. It's re-initialized on each call otherwise.

Secondly, the 10000 in clearTimeout(fnInterval, 10000) isn't a valid parameter. clearTimeout(timeoutId) accepts only the first parameter and clears the timeout passed in immediately. You'd need a setTimeout to trigger this after 10 seconds, if that's your goal. But that causes a race condition between the two timeouts -- imprecision can mean you'll miss some of the logs or wind up with extra logs.

Using a counter is one solution, as other answers show, but usually when I'm using complex timing with setInterval that requires clearing it after some number of iterations, I refactor to a generic promisified sleep function based on setTimeout. This keeps the calling code much cleaner (no callbacks) and avoids messing with clearTimeout.

Instead of a boolean to flip a flag back and forth between two messages, a better solution is to use an array and modulus the current index by the messages array length. This makes it much easier to add more items to cycle through and the code is easier to understand since the state is implicit in the counter.

const sleep = ms => new Promise(res => setInterval(res, ms));

(async () => {
  const messages = ["hi", "bye"];
  
  for (let i = 0; i < 10; i++) {
    console.log(messages[i%messages.length]);
    await sleep(1000);
  }
})();

about 4 years ago · Juan Pablo Isaza Denunciar

0

setInterval() is stopped by clearInterval() not clearTimeout(). Details are commented in code below.

// Define a counter
let i = 0;
// Define interval function
const fnCount = setInterval(fnSwitch, 1000);

function fnSwitch() {
  // Increment counter
  i++;
  // if counter / 2 is 0 log 'HI'
  if (i % 2 === 0) {
    console.log(i + ' HI');
    // Otherwise log 'BYE'
  } else {
    console.log(i + ' BYE');
  }
  // If counter is 10 or greater run fnStop()
  if (i >= 10) {
    fnStop();
  }
};

function fnStop() {
  // Stop the interval function fnCount()
  clearInterval(fnCount);
};

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