[Solved]Why does the speed of increment in the code fluctuate?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 9

[Solved]Why does the speed of increment in the code fluctuate??

I wanted to make a code to Increment the variable after a fixed time interval.. But in my code the variable is incremented at given speed for sometime at the start.. But if user clicks the button rapidly the variable is then incremented rapidly even when the user isn't pressing the button.. 😕 Also I don't know of i should post this in Q&A section or my personal post... 😅 Any help is appreciated!! https://code.sololearn.com/W4H9Lfmsfj4h/?ref=app

26th Sep 2018, 5:05 AM
$hardul B
$hardul B - avatar
3 Answers
+ 3
/*hi $hardul, its because you are creating new loop everytime you click. So if you dont want that to happen then clear the interval before starting new */ var i=0; var myInterval; function auto() { if(myInterval !== undefined){ clearInterval(myInterval); } document.getElementById("out").innerHTML=i; myInterval = setInterval(auto1,3000); } function auto1() { i=i+1; document.getElementById("out").innerHTML=i; }
26th Sep 2018, 1:55 PM
Morpheus
Morpheus - avatar
+ 4
Pressing more time on button would make more setInterval calls, multiple timers update of course make the increment run rapidly.
26th Sep 2018, 5:12 AM
Calviղ
Calviղ - avatar
+ 3
Thank you Morpheus and Calviղ
26th Sep 2018, 1:57 PM
$hardul B
$hardul B - avatar