Skip to content
Advertisement

Why do I need to call clearTimeout twice to reset setTimeout

I ran into a puzzle as I was trying to make a rotating banner in JavaScript following this tutorial.

All the images were displayed at fixed intervals with setTimeout. Later I would like to add a button that allows the user to switch to the next image on the banner manually, so I thought I would use clearTimeout to stop the timer for the automatic switching first and then reset it after the manual switch. However, I was confused by the fact that I had to call clearTimeout twice in order to stop the original timer properly before resetting it. Calling clearTimeout once could not stop the timer properly. Can anybody please help explain why is that the case to me? Is there anything wrong with my code? Below is part of the code:

JavaScript

Many thanks for your help!

Advertisement

Answer

I tested this and seems to work fine with calling only once, that said, this seems to be better suited to use setInterval() instead of setTimeout(). Also reducing some unnecessary code repetition.

See example using just text instead of replacing an img‘s source.

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement