How to access variables in another scope inside a function using closure in javascript? -


i have following function makestopwatch trying work through better understand javascript closures:

var makestopwatch = function() {   var elapsed = 0;   var stopwatch = function() {     return elapsed;   };   var increase = function() {     elapsed++;   };    setinterval(increase, 1000);   return stopwatch; };  var stopwatch1 = makestopwatch(); var stopwatch2 = makestopwatch();  console.log(stopwatch1()); console.log(stopwatch2()); 

when console.log calls stopwatch1 , stopwatch2 0 returned each time respectively.

as understand intended functionality of makestopwatch variable elapsed 0 if returned inner function stopwatch. inner function increase increments variable elapsed. setinterval calls increase after delay of 1 second. finally, stopwatch returned again time updated value expected 1.

but doesn't work because inside makestopwatch, inner stopwatch, increase, , setinterval functions in independent scopes of 1 another?

how can revise work understand elapsed incremented , value closed on , saved when assign makestopwatch variable stopwatch1 , call stopwatch1 updated value returned?

var makestopwatch = function() {   var elapsed = 0;    // stopwatch function referenced later   var stopwatch = function() {     return elapsed;   };    var increase = function() {     elapsed++;   };   // setinterval continue running , calling increase function.   // not maintain access it.   setinterval(increase, 1000);    // returns stopwatch function reference earlier.  way   // can interact closure variables through function.   return stopwatch; };  var stopwatch1 = makestopwatch(); // runs makestopwatch function.  function *returns* // inner stopwatch function emphasized above.  console.log(stopwatch1()); // stopwatch1 reference inner stopwatch function.  no longer // have access elapsed variable or function increase.  // `setinterval` calling `increase` still running.  every // 1000ms (1 second) increment elapsed 1. 

so if were put of above code console, , call console.log(stopwatch1()) sporadically, console.log number of seconds since created stopwatch.


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -