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!' />