JSDev: Closure Example

Uses closure to fire an alert every third click on a button.

by David McClelland

HTML

<input type="button" value="closure" id="button"/>

JavaScript

var element = document.getElementById('button');

element.onclick = (function() {
    // init the count to 0
    var count = 0;

    return function(e) {  // <- This function becomes the onclick handler
        count++;          //    and will retain access to the above `count`

        if (count === 3) {
            // do something every third time
            alert("Third time's the charm!");
            //reset counter
            count = 0;
        }
    };
})();