Button for starting a timer in JavaScript

In the previous lessons, our timer started its work as soon as the page loaded. Let's now make a button, by clicking on which our timer will start:

<button id="start">start</button>

Let's write the appropriate JavaScript:

let start = document.querySelector('#start'); start.addEventListener('click', function() { let i = 0; setInterval(function() { console.log(++i); }, 1000); });

Make a button, by clicking on which a countdown will be displayed in the console, starting from 100.

Multiple pressing of the button

The code I provided above actually has some problem. This problem manifests itself if our button is clicked several times. In this case, each click will start a new timer.

That is, for example, three clicks on the button will cause three timers to be launched, and each of these timers will output the value of the counter to the console. This means that the values will change three times faster!

To solve the described problem, you just need to make sure that pressing the button again does not lead to a new start of the timer. For example, after the start of the timer, you can unbind the attached click handler from the button:

let start = document.querySelector('#start'); start.addEventListener('click', function func() { let i = 0; setInterval(function() { console.log(++i); }, 1000); this.removeEventListener('click', func); // unbinds the handler });

Take your solution to the previous problem. Check that pressing the button repeatedly speeds up the countdown. Fix this issue.

enru