(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
The global clearTimeout() method cancels a timeout previously established by calling setTimeout() .
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With