0

I'm about to make some JS functionality that will

  • execute one function for previously predefined number of times (iterations)
  • make a delay after each function execution for previously predefined number of seconds

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.

2
  • 1
    Have you heard of `window.setTimeout()'? Commented Nov 7, 2012 at 11:00
  • I was actually thinking of for loop in JS, but if there's better way... Commented Nov 7, 2012 at 11:06

3 Answers 3

2
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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use -

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

Ref -

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.