Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript clearTimeout not working

Tags:

(I've looked at all similar questions/answers but none of them solve my problem.)

The code:

var timeoutHandle;  function showLoader(show) {     if (show) {         $('.loader').html('Loading...');         $('.loader').show();          timeoutHandle = setTimeout(function () {             if ($('.loader').is(':visible')) {                 $('.loader').html('Still loading...');             }         }, 15000);     }     else {         $('.loader').hide();         clearTimeout(timeoutHandle);     } } 

The AJAX function simply calls showLoader(true) before calling the server, and then showLoader(false) after a result. I still sometimes see the text change from "Loading..." to "Still loading..." long before 15 seconds, so it's as if a timer thread is still running. Is there something wrong with the code above? Or could the problem be with other code..

edit: I must add that showLoader(true) can be called again (and again) before a response from the server

like image 380
notAnonymousAnymore Avatar asked Jun 28 '13 15:06

notAnonymousAnymore


People also ask

What does clearTimeout do in JavaScript?

The global clearTimeout() method cancels a timeout previously established by calling setTimeout() .

What does clearTimeout return?

Category: Control. Clears an existing timer by passing in the numeric value returned by setTimeout(). Sometimes you need to clear a timeout timer before it executes. clearTimeout() uses the value returned by the setTimeout(function, milliseconds) function.

Does clearTimeout stop execution?

Methods setTimeout(func, delay, ... args) and setInterval(func, delay, ... args) allow us to run the func once/regularly after delay milliseconds. To cancel the execution, we should call clearTimeout/clearInterval with the value returned by setTimeout/setInterval .

How do you set clear timeout?

You need to pass the amount of time to wait for in milliseconds , which means to wait for one second, you need to pass one thousand milliseconds . To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.


1 Answers

You should add a check to see if there is already a timeoutHandle before creating a new one.

try this:

if(timeoutHandle){     clearTimeout(timeoutHandle);     timeoutHandle = null; } timeoutHandle = setTimeout(function () {     if ($('.loader').is(':visible')) {         $('.loader').html('Still loading...');     } }, 15000); 

and then in the else case set timeoutHandle to null after you clear it like so:

clearTimeout(timeoutHandle); timeoutHandle = null; 

This will eliminate the chance of you creating concurrent timeouts if showLoader(true) function is called more than once.

like image 61
DiverseAndRemote.com Avatar answered Oct 11 '22 13:10

DiverseAndRemote.com