Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause jQuery code for few milliseconds?

I'm using jQuery Ajax functions to auto update my database through cron. Since there are a lot of rows to be updated, I'd like to pause the code for few milliseconds each iretation. What would be the best way to do it?

Here's sample of my code:

<?php

    $zdroje = $db->select('zdroje', 'id!=1');

    echo "<script type='text/javascript'>\n
            $(document).ready(function() {\n"; 

    foreach($zdroje as $zdroj) {

    echo "$.post( '/adminator/menu/2zajezdy/tools/01otnXml/requests.php', { 'updateXML': '".$zdroj['id']."' }, function(data) {
        // pause here!
    });\n";

    } // end: foreach

    echo "});\n</script>\n";

?>
like image 905
Mike Avatar asked Apr 16 '26 05:04

Mike


2 Answers

There are only two ways to do this:

  1. Use setTimeout (for example, 10 milliseconds):

    setTimeout(function () {
        $.post( '/adminator/menu/2zajezdy/tools/01otnXml/requests.php', { 'updateXML': '".$zdroj['id']."' }, function(data) {
            // do stuff here!
        });
    }, 10);
    
  2. For loop (this is a hack, so this is not preferred):

    for(i = 0; i < 500; i++);

like image 66
beatgammit Avatar answered Apr 18 '26 17:04

beatgammit


I suggest you take a look at jQuery's new defer system. Here's a good tutorial: http://www.erichynds.com/jquery/using-deferreds-in-jquery/

Essentially, you can create a "hold" promise like this:

function hold(delay){
    var dfd = $.Deferred();

    setTimeout(function(){
        dfd.resolve();
    }, delay);

    return dfd.promise();
}

Then string together ajax requests with it like this:

$.when($.post('yourLongUrlHere'))
    .then(hold(500))
    .then($.post('anotherUrl'))
    .then(hold(500))
    .then($.post('somethingElse.php'));

This will make each ajax request in order waiting 500 miliseconds in between each.

Should handle what you asked about w/o a problem.

like image 24
Shakakai Avatar answered Apr 18 '26 18:04

Shakakai