You don't show us much of your code in the real context, but some of the common reasons for not successfully clearing the previous timer are:
Your variable that holds the timer is not a global variable (or in a closure that persists) and thus doesn't survive from one call to the next so when you go to do
clearTimeout(refresh)
, therefresh
variable doesn't hold the right value. You can check this by doing aconsole.log(refresh)
before you do theclearTimeout()
. If this is your problem, thenrefresh
will probably beundefined
.You're accidentally starting more than one timer thus you're overwriting your
refresh
variable and yourclearTimeout(refresh)
only stops that last timer set, not the earlier one. In some forms of code, it's safest to always doclearTimeout()
on any prior timer BEFORE you start a new timer to make sure you didn't already have one running or it may make more sense to just check with anif
statement if you already have one running.
If you want more specific help, you will need to disclose more details of your ACTUAL code because the four lines of code you have above in that exact sequence and all in the same scope do not have the problem you are experiencing - so obviously there's more to the actual code than you've disclosed.