Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 804
oshirowanen Avatar asked Dec 07 '22 23:12

oshirowanen


2 Answers

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 :)

like image 146
Sarfraz Avatar answered Dec 18 '22 23:12

Sarfraz


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.

like image 25
alex Avatar answered Dec 19 '22 00:12

alex