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

0

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)

javascript
2021-11-24 06:12:17
3

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.

2021-11-24 08:11:57
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);
  }
})();

2021-11-24 06:17:50
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);
};

2021-11-24 06:31:05

In other languages

This page is in other languages

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................