Download 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);
    });
});

In the following HTML:

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

For some reason, the part is setTimeoutnot working. that is, it does not seem to call the function after 5000 ms.

jsFiddle .

+3
source share
3 answers

You need to replace:

setTimeout("simulate_ajax_call()", 5000);

with:

setTimeout(simulate_ajax_call, 5000);

Check working example


You should avoid placing ()at the end of the function name, because otherwise it is immediately called / launched :)

+9
source

You need to drop quotes and brackets .

Executing is setTimeout("simulate_ajax_call()", 5000)equivalent eval()to entering this code, which automatically starts the function.

+4
source

setTimeout eval , simulate_ajax_call , eval , .

As the other two answers show, the best way to solve the problem is to use the transfer function setTimeout, but carefully remove the parentheses because you do not want to accidentally call the function immediately.

Perhaps your code would work if you declared simulate_ajax_callin a global scope. The brackets would be correct in this case, although the string version setTimeoutis still a bad idea.

+1
source

Source: https://habr.com/ru/post/1791811/


All Articles