Closure in JavaScript - Stop Watch

Closure in JavaScript - Stop Watch

by Nirvanachain

HTML

<!--
http://www.kirupa.com/html5/closures_in_javascript.htm?utm_source=javascriptweekly&utm_medium=email
-->

JavaScript

function stopWatch () {
     
    var startTime = Date.now();
    
    function getDelay () {
        
        var elapsedTime = Date.now() - startTime;
        
        alert(elapsedTime);
        
    };
    
    return getDelay;
    
};

var timer = stopWatch();

//do something that takes some time
for (var i = 0; i < 1000000; i++) {
    var foo = Math.random() * 10000;   
};

//invoke the returned function
timer(); //you'll see a dialog displaying the number of milliseconds it took between your timer variable getting
         //initialized, your for loop running to completion, and the timer variable getting invoked as a function.
         //Basically, you have a stopwatch that you invoke, run some long-running operation, and invoke again to
         //see how long the long-running operation took place.

/**
To review this one more time using our existing example, the startTime variable gets the value of Date.now the moment the timer variable gets initialized and the stopWatch function runs. When the stopWatch function returns the inner getDelay function, the stopWatch function goes away. What doesn't go away are any shared variables inside stopWatch that the inner function relies on. Those shared variables are not destroyed. Instead, they are enclosed by the inner function aka the closure.
**/