Sally Moulton
Sally Moulton

Reputation: 21

Putting a 10 second pause in xmlHttpRequest submit

This javascript code is fairly lengthy, but the most important part is the end where it posts:

 httpwp['send'](paramswp);

I have tried without success to put a 10 second pause between each send. Normally it sends them all instantly.

full code http://pastebin.com/cEM7zksn

Upvotes: 2

Views: 918

Answers (2)

nnnnnn
nnnnnn

Reputation: 150040

The setTimeout() function does not pause execution for the specified time, it queues a function to be executed after the specified time. The line of code after setTimeout() will be executed immediately. So if you have the following code:

1 someFunction();
2 setTimeout(function(){console.log("From timeout");}, 10000);
3 console.log("After setTimeout()");

What will happen is on line 1 someFunction() will be called, then on line 2 an anonymous function will be queued to execute in 10 seconds time, then line 3 will execute, logging "After setTimeout()", and finally 10 seconds later the anonymous function will execute logging "From timeout".

If you want to code a loop where each iteration is spaced out by 10 seconds, rather than using a conventional for loop you write a function that uses setTimeout() to call itself:

// this for loop won't work

for(var i = 0; i < 20; i++) {
   // do something

   // pause for 10 seconds ---- can't be done
}

// so instead you do something like this:

function timeoutLoop(i, max) {
   if (i < max) {
      // do something

      i++;
      setTimeout(function(){timeoutLoop(i, max);}, 10000);
   }
}
timeoutLoop(0, 20);

I found your code a little hard to read so I've not tried to integrate the above with it, but here is a really simple demo of the above working: http://jsfiddle.net/CrSEt/1/

Or here is a cleaner version that separates the actual processing from the loop function by using a callback: http://jsfiddle.net/CrSEt/

I'm sure if you play around a bit with the above you'll see how to get it to work in your code. You may want to consider setting subsequent timeouts from inside your ajax success callback.

Upvotes: 1

Adam Rackis
Adam Rackis

Reputation: 83356

To delay 10 seconds before calling this, you could use setTimeout

setTimeout(function() { httpwp['send'](paramswp); }, 10000);

Or more simply:

setTimeout(function() { httpwp.send(paramswp); }, 10000);

Upvotes: 2

Related Questions