- Since there were no synchronous calls, there was nothing on the call stack and therefore it just ran
- Maybe some sort of mechanism was needed to prevent this from occurring
However, the real reason was that I’d invoked the setInterval() function and assigned it’s return to a variable (erroneously thinking I’d created a named function by assigning an anonymous function to a variable, which was contained within the setInterval()). So the asynchronous setInterval() was running when the script loaded and updated the innerHTML of the element it was attached to. [see commit]
This was sorted by enclosing the setInterval call within a function and then invoking that on the button’s onclick event. [see commit] The next item was to stop the timer once it was started. But that had its own issue in that the timer would not stop. Turned out that the id returned by the setInterval function was scoped to the first conditional branch and would not transfer over to the second conditional:
Placing the variable outside the conditionals, but still within the function body, resulted in the same thing. The variable had to be declared outside the function’s scope – read more about scope here – as declaring the variable without the var keyword still does not set its scope to global. The latest commit with all the issue fixes can be found in this commit [see commit].
So that still leaves the two outstanding requirements from the first post, as well as a new one (which is just to refactor the two buttons to just one for starting and stopping the timer):
- Being able to capture snapshots of the timer countdown on a button press.
- Clearing the snapshots and resetting the timer on another button press.