Created a simple Timer

function timer() { setInterval(function timer() { var label = document.getElementById('label'); label.innerHTML = parseInt(label.innerHTML) + 1; }, 1000); } 

So how can you stop it inside another function? Without using jQuery!

  • in the current form - no way. setInterval - returns the timer id to which you can apply clearInterval, but since now all this remains inside the timer function - there is nothing to be applied to clearInterval - Grundy

2 answers 2

 var i = 0; var timerId = 0; function timer() { timerId = setInterval(function () { //Π—Π΄Π΅ΡΡŒ ΠΊΠΎΠ΄ Π² Ρ†ΠΈΠΊΠ»Π΅ console.log(i++); }, 1000); } function stopTimer(){ clearInterval(timerId); } 
 <input type="button" value="StartTimer" onclick="timer()" /> <br> <input type="button" value="StopTimer" onclick="stopTimer()" /> 

setInterval returns the id to be sent to clearInterval (id), in order to stop, see the example

  • Well, I want to stop the function by clicking, but not after a certain amount of time - arthru
  • updated example, call stopTimer, right? - MrFylypenko
  • Is it possible to specifically example with my code? - arthru

The setTimeout and setInterval functions return an identifier that can be passed to the clearTimeout and clearInterval stop timer functions, respectively.
You just need to save the returned id and, if necessary, pass it to the cleaning function.
For example:

 function timer() { // БохраняСм Π² свойствС ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π° Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ, ΠΈΠ½Π΄ΠΈΠ²ΠΈΠ΄ΡƒΠ°Π»ΡŒΠ½ΠΎ ΠΈ внСшниС ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½Ρ‹Π΅ Π½Π΅ Π½ΡƒΠΆΠ½Ρ‹ timer.id = setInterval(() => { let label = document.querySelector('#label'); label.innerHTML = (parseInt(label.innerHTML) || 0) + 1; }, 1000); } // По ΠΊΠ»ΠΈΠΊΡƒ запускаСм Ρ‚Π°ΠΉΠΌΠ΅Ρ€ document.querySelector('#start').addEventListener('click', e => timer()); // По ΠΊΠ»ΠΈΠΊΡƒ запускаСм Ρ„ΡƒΠ½ΠΊΡ†ΠΈΡŽ очистки, Ρ‚. ΠΊ. timer.id - Π½Π΅ ΠΏΡ€ΠΈΠ²Π°Ρ‚Π½ΠΎΠ΅ свойство // PS Кнопкой старта ΠΌΠΎΠΆΠ½ΠΎ ΠΏΡ€ΠΎΠ΄ΠΎΠ»ΠΆΠΈΡ‚ΡŒ счёт document.querySelector('#stop').addEventListener('click', e => clearInterval(timer.id)); 
 <div id='label'>0</div><br /> <input type='button' id='start' value='Start!' /><br /> <input type='button' id='stop' value='Stop!' /> 

  • Is it possible that he himself would not start? - arthru
  • @arthru, of course - just do not start the timer(); function timer(); (8th line JS ). Then you need to call it where you need - a click handler, March 5th on the clock or 4:30 on the calendar. - user207618
  • And how can you click on the button? - arthru
  • @arthru, updated the answer. - user207618