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

166
Views
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 answers
Answer question

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 Report

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 Report

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 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!