0

The title may be misleading, but it's essentially what I need to accomplish.

I have an AJAX "Loading" text that I want to update if the server has taken more than 15 seconds to respond.

Here is the code:

$(".loader").html('Loading');
$(".loader").show();
setTimeout(function () {
    if ($('.loader').is(":visible")) {
        $(".loader").html('Click <a href="javascript:location.reload()">here</a> to reload.</span>');
    }
}, 15000);

Is there a better approach? When I eventually call $(".loader").hide(); I want the setTimeout counter to be aborted. Is it possible?

1

3 Answers 3

5

Sure. setTimeout returns a value you can pass to clearTimeout in order to stop timeout.

var handle = setTimeout(function () {
    alert("Oh noes, I ran!")
}, 5000)

clearTimeout(handle)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the clearTimeout function:

$(".loader").html('Loading');
$(".loader").show();
var timerId= setTimeout(function () {
    if ($('.loader').is(":visible")) {
        $(".loader").html('Click <a href="javascript:location.reload()">here</a> to reload.</span>');
    }
}, 15000);

$(".stop").click(function () {
    clearTimeout(timerId);
    $(".loader").html("done");
});

See this fiddle: http://jsfiddle.net/KaNUP/

Comments

-1

I would recommend to make a shorter period (1 sec) and increment counter inside function you call. Then you can exit on successfull load or counter threshold, whichever comes earlier.

3 Comments

setTimeout != setInterval, and a counter would either require a closure (which is overkill in this case) or a global variable, which is evil, in any case
@EliasVanOotegem I'm aware about differences between those function. And I did, what I proposed before. And this is not a place, where you argue, whether global variables or goto operator or eval() is evil. Every tool suites it's task.
Aw come on... spite Down-vote? really? I didn't even DV your answer, but I just commented because I can't stand DV's whithout explanation... I just wanted to help you understand why some people might find your approach counter-productive or even "bad practice". PS: When it comes to eval being evil: there is no discussion now that JSON.parse has been implemented in all browsers... I've written code for 9 years, 4 of which professionally, and I've never ever needed eval...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.