Miloš Đakonović
Miloš Đakonović

Reputation: 3871

Repeating Javascript function execution with time delay

I'm about to make some JS functionality that will

One big request is that solution must be Ajax compatibile.

Say:

<script>
functon my_function(numberoftimes, secondsdelay){
//do ajax requests for numberoftimes, separeted by secondsdelay
$.ajax(
            {
                type: "GET/POST",
                url: "exampleurl",
                data: "key=value",
            }
        )
}
<script>

<button onclick="my_function(3,1)">Do it</button>

how?

Thanks.

Upvotes: 0

Views: 209

Answers (3)

Mihai
Mihai

Reputation: 2760

Use

setInterval()

in your ajax callback and keep a contor of how many times you ran the function. and on the callback just do

callback : function() {
    contor++;
    if(contor < 3) {
       setInterval(yourFunction, delayMilliseconds)
    }
}

Upvotes: 0

Sayem Shafayet
Sayem Shafayet

Reputation: 159

Use -

window.setInterval("javascript function",milliseconds);

Ref -

http://www.w3schools.com/js/js_timing.asp

Upvotes: 0

Esailija
Esailija

Reputation: 140220

function my_function(numberoftimes, secondsdelay) {
    //do ajax requests for numberoftimes, separeted by secondsdelay
    var i = 0;

    function doIt() {
        $.ajax({
            type: "GET/POST",
            url: "exampleurl",
            data: "key=value",
            complete: function() {
                if (i++ < numberoftimes) {
                    setTimeout(doIt, secondsdelay * 1000);
                }
            }
        });
    }

    doIt();
}

Upvotes: 2

Related Questions