开发者

Loading message and setTimeout

I have the following script:

$(function() {
    $(".message").hide();

    function simulate_ajax_call()
    {
        $.ajax({
            url: "/echo/json/",
            success: function(){
                alert("done");
                $(".message").empty().html("done");
                $(".message").delay(1000).fadeOut(500);
            }
        });
 开发者_高级运维   }

    $('.button').click(function() {
        $(".message").fadeIn(500);
        setTimeout("simulate_ajax_call()", 5000);
    });
});

With the following HTML:

<input type="button" value="button" class="button" />
<div class="message">loading...</div>

For some reason the setTimeout part is not working. i.e. it does not seem to call the function after 5000ms.

jsFiddle.


You need to replace:

setTimeout("simulate_ajax_call()", 5000);

with:

setTimeout(simulate_ajax_call, 5000);

Check out the working example


You should avoid putting () at the end of the function name because otherwise it gets called/run immediately :)


You need to drop the quotes and the parenthesis.

Doing setTimeout("simulate_ajax_call()", 5000) is equivalent of eval()ing that code, which is automatically running the function.


setTimeout evals its string argument in the global scope, but simulate_ajax_call is declared in a nested scope, so the eval can't find it in order to invoke it.

As the other two answers point out the best way to resolve the issue is to use the function-passing version of setTimeout, but being careful to remove the parentheses, because you don't want to accidentally invoke the function immediately.

Your code would probably have worked had you declared simulate_ajax_call at the global scope. The parentheses would have been correct in this case, although the string version of setTimeout is still a bad idea in general.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜