Skip to content
Advertisement

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)

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement