Persistent variables instead of global variables in JavaScript

I want to have a single button that acts as a start and stop button for some recurring time events.

To do this, I can have a global variable at the top of everything:

toggleOn = false; 

And then, inside <button onClick="..., I can have:

toggleOn =! toggleOn;
foo(); 
function foo() {
  // do my stuff
  if (toggleOn) {
    setTimeout(foo, 5000);
  }
}

But the problem is that I should not use a global variable to perform the same task. How am I supposed to do this? Is there a persist variable that can carry a value outside its scope?

+4
source share
3 answers

This is an example of how closure is a great feature of the language.

(function()
{
    var active = false;
    myButton.addEventListener('click', function myButtonClick(event)
    {
        if (active) {
            // recursion..?
            setTimeout(myButtonClick, 5000);
        }

        active = !active;
    }
})();

More on closing here .

+4

javascript. - :

var handler = function () {
  var private_state = true;
  return function() {
    private_state = !private_state;
    if (private_state) {
      // Do something
    }
  }
}();

handler onclick.

+2

Earlier answers have already been noted that you can use locks to store the "private" variable, which will monitor the state. Alternatively, you can use HTML5 data to save this.

HTML

<button data-toggleOn="false">Click me!</button>

Javascript

button.addEventListener('click', function() {
  var toggleOn = this.dataset.toggleOn = !JSON.parse(this.dataset.toggleOn);

  if (toggleOn) {
    // do stuff!
  }
});

and if you use jQuery ..

$('button').click(function() {
  var toggleOn = !$(this).data('toggleOn');
  $(this).data('toggleOn', toggleOn);
});
0
source

All Articles