0

I want a variable's value regularly changing between 0 and 1. If I have a variable whose value is 0 (counter = 0), how can I increase it by 1 (counter = 1) after a few seconds, then decrease it back to 0 ( counter = 0) after another few seconds? An endless loop basically is what I want.

I'm assuming this will require setTimeout or setInterval, but I've absolutely no idea how I'd go about this. I'm very unfamiliar with the syntax; I'm very much a newbie. Does anyone have any pointers?

Thanks!

5 Answers5

1

You can create an endless, timed loop by having a function that calls itself at the end via setTimeout. See below.

var count = 0;
function flip() {
  count = Number(!count);
  console.log(count);
  setTimeout(flip, 1000);
}

flip();
cstricklan
  • 662
  • 4
  • 13
1

A more generic approach:

// possible addition: allow user to stop the timer
const rotate = (time, vals) => {
  // TODO: handle incorrect vals (non-empty array) or time (positive number)
  let idx = 0;
  setInterval(() => idx = (idx + 1) % vals.length, time);
  return {
    get val() {return vals[idx];}
  }
}

const toggle = rotate(1000, [0, 1])

toggle.val //=> depends on when you call it, changes every 1000 ms
           //   but always either 0 or 1.

One advantage of this is that it doesn't keep the value in global scope where someone else can mess with it, but encapsulates it in a closure.

It's more generic because you can easily change the time between updates and you can choose whatever you want for values (for example, rotate(5000, ['foo', 'bar', 'baz').)

Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
0
var counter = 0;
var changeCounter = function () {
  counter = counter === 0 ? 1 : 0;
  console.log('counter', counter);
  setTimeout(changeCounter, 1000);
}
changeCounter();
Dmitry Druganov
  • 2,088
  • 3
  • 23
  • 32
0

This sounds like homework but try this:

var value = 0;

setInterval(
  function() {
    value = value===0 ? 1 : 0;
    console.log('value =', value);
  },
  1000
);

setInterval will call the function over and over again without needing to call setTimeout over and over again.

Intervalia
  • 10,248
  • 2
  • 30
  • 60
0

setInterval is what you want, as documented in W3C, you should pass a function and a time interval in milliseconds on how often to execute the code.

var counter = 0;

setInterval(function(){ 

  counter = 1 - counter;

  //Do what you want with the result...
  //alert(counter);  

}, 1000);

https://codepen.io/paulodiogo/pen/xPPOKa?editors=1010

Not using global variable... https://codepen.io/paulodiogo/pen/KyyMXZ