如何暂停jQuery代码几毫秒?

问题描述 投票:2回答:6

我正在使用jQuery Ajax函数通过cron自动更新我的数据库。由于有很多行需要更新,我想暂停代码几个毫秒的每次创建。最好的方法是什么?

这是我的代码示例:

<?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";

?>
javascript jquery delay
6个回答
6
投票

只有两种方法可以做到这一点:

  1. 使用setTimeout(例如,10毫秒): setTimeout(function () { $.post( '/adminator/menu/2zajezdy/tools/01otnXml/requests.php', { 'updateXML': '".$zdroj['id']."' }, function(data) { // do stuff here! }); }, 10);
  2. For loop(这是一个hack,所以这不是首选): for(i = 0; i < 500; i++);

4
投票

我建议你看看jQuery的新推迟系统。这是一个很好的教程:http://www.erichynds.com/jquery/using-deferreds-in-jquery/

从本质上讲,您可以创建这样的“保留”承诺:

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

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

    return dfd.promise();
}

然后用它将ajax请求串起来:

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

这将使每个ajax请求按顺序在每个之间等待500毫秒。

应该处理你没有问题的问题。


3
投票

你可以试试.delay()函数......

http://api.jquery.com/delay/


1
投票

一个笨拙的方法可能是使用JavaScript的setTimeout()方法,但我建议你看看jQuery函数,$.ajaxComplete()$.ajaxStart()$.ajaxStop()


1
投票

我想你想要生成链式调用而不是普通列表。即你现在得到的是:

$.post(...)
$.post(...)
...
$.post(...)

你想得到这样的东西:

$.post(url1, function(data) {
    setTimeout(function() {
        $.post(url2, function(data) {
            setTimeout(function() {$.post(url3)}, 500);
        });
    }, 500);
});

如果您正在使用PHP生成JavaScript代码 - 生成像这样的代码应该不会太难。希望这可以帮助。

编辑:尝试像这样生成它

$code = "%s";
foreach($sources as $source) {
   $part = "$.post( '/adminator/menu/2zajezdy/tools/01otnXml/requests.php', { 'updateXML': '${source['id']}' }, function(data) {
      setTimeout(function() {
         %s
      }, 500);
   });"
   $code = sprintf($code, $part);
}
$code = sprintf($code, '');

0
投票

您无法暂停JavaScript引擎处理代码。 JS具有异步运行的代码 - 例如,来自AJAX请求的响应返回并执行回调函数。

setTimeout是关于延迟特定函数执行的最好朋友。

//Executes an alert exactly 1 second later
setTimeout(function() {
   alert('hello world'); 
}, 1000);
© www.soinside.com 2019 - 2024. All rights reserved.