I have the following function makeStopwatch that I am trying to work through to 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 I console.log the calls to stopwatch1 and stopwatch2 I get 0 returned each time respectively.
As I understand the intended functionality of makeStopwatch the variable elapsed would be 0 if returned by the inner function stopwatch. The inner function increase increments the variable elapsed. Then setInterval calls increase after a delay of 1 second. Finally, stopwatch is returned again this time with the updated value which is expected to be 1.
But this doesn't work because inside makeStopwatch, the inner stopwatch, increase, and setInterval functions are all in independent scopes of one another?
How can I revise this to work as I understand it so that elapsed is incremented and that value is closed over and saved so that when I assign makeStopwatch to variable stopwatch1 and call stopwatch1 the updated value is returned?
console.log(stopwatch1())multiple times.)setTimeout(console.log(stopwatch1()), 2000);setTimeout(console.log(stopwatch2()), 4000);for example to see that the stopwatches are indeed "running"increaseand howelapsedis incremented, as well as taking into my perception of what a real-world stopwatch does, I expect the console.logs to show that the stopwatch is indeed counting upwards.setTimeout(function() {console.log(stopwatch1())}, 2000);and the same forstopwatch2.