在重复的jQuery / Ajax函数中设置延迟

我试图为可重复的查询添加延迟。

我发现.delay不是这里使用的。 相反,我应该使用setInterval或setTimeout。 我试过了两个,没有任何运气。

这是我的代码:

  $(setInterval(function () { $.ajax({ cache: false, url: 'ajax2.php', data: "workerID=", dataType: 'json', success: function(data) { var id = data[0]; //get id var vname = data[1]; //get name //-------------------------------------------------------------------- // 3) Update html content //-------------------------------------------------------------------- $('#output').html("id: "+id+" name: "+vname); } }); }),800);   

代码工作正常,它按要求输出结果。 它只是没有延迟的负载。 时间和/或间隔似乎不起作用。

谁知道我做错了什么?

我永远不明白为什么人们总是间隔地添加他们的AJAX请求,而不是让成功的AJAX调用只是自己调用,同时冒着严重的服务器负载通过多个请求而不仅仅是在你成功回来后再拨打一个电话。

有鉴于此,我喜欢编写解决方案,其中AJAX调用只是在完成时调用自己,如:

 // set your delay here, 2 seconds as an example... var my_delay = 2000; // call your ajax function when the document is ready... $(function() { callAjax(); }); // function that processes your ajax calls... function callAjax() { $.ajax({ // ajax parameters here... // ... success: function() { setTimeout(callAjax, my_delay); } }); } 

我希望这是有道理的! 🙂

更新:

在再次审阅之后,我注意到原始问题中的PHP代码中也存在一个问题,我需要澄清和解决。

虽然上面的脚本在创建AJAX调用之间的延迟方面效果很好,但是当添加到原始post中的PHP代码时,脚本将只是与SQL查询选择的行数一样多次回显,创建多个函数具有相同的名称,并可能同时进行所有AJAX调用……根本不是很酷……

考虑到这一点,我提出了以下附加解决方案 – 使用PHP脚本创建一个array ,该array可以被JavaScript一次消化,以实现所需的结果。 首先,PHP构建JavaScript数组字符串……

  

接下来,用JavaScript来消化和处理我们刚创建的数组……

 // set your delay here, 2 seconds as an example... var my_delay = 2000; // add your JavaScript array here too... var my_row_ids = ; // call your ajax function when the document is ready... $(function() { callAjax(); }); // function that processes your ajax calls... function callAjax() { // check to see if there are id's remaining... if (my_row_ids.length > 0) { // get the next id, and remove it from the array... var next_id = my_row_ids[0]; my_row_ids.shift(); $.ajax({ cache : false, url : 'ajax2.php', data : "workerID=" + next_id, // next ID here! dataType : 'json', success : function(data) { // do necessary things here... // call your AJAX function again, with delay... setTimeout(callAjax, my_delay); } }); } } 

注意:Chris Kempen的答案(上图)更好。 请使用那个。 他在AJAX例程中使用了这种技术 。 请参阅此答案 ,了解使用setTimeout优于setInterval的原因。


 //Global var is_expired = 0; $(function (){ var timer = setInterval(doAjax, 800); //At some point in future, you may wish to stop this repeating command, thus: if (is_expired > 0) { clearInterval(timer); } }); //END document.ready function doAjax() { $.ajax({ cache: false, url: 'ajax2.php', data: "workerID=", dataType: 'json', success: function(data) { var id = data[0]; //get id var vname = data[1]; //get name //-------------------------------------------------------------------- // 3) Update html content //-------------------------------------------------------------------- $('#output').html("id: "+id+" name: "+vname); } }); //END ajax code block } //END fn doAjax() 

我已经设计了一个包装器方法 ,它在默认的$.ajax方法的基础添加了一个自定义延迟。 这是一种在整个应用程序中(在所有 jQuery ajax调用上)延迟的方法。

在模拟真实的随机延迟方面非常方便。

 (function(){ $._ajaxDelayBk = $.ajax; // save reference to the "real" ajax method // override the method with a wrapper $.ajax = function(){ var def = new $.Deferred(), delay = typeof $.ajax.delay == 'undefined' ? 500 : $.ajax.delay, delayTimeout, args = arguments[0]; // set simulated delay (random) duration delayTimeout = setTimeout(function(){ $._ajaxDelayBk(args) .always(def.resolve) .done(def.resolve) .fail(def.reject) }, delay); def.abort = function(){ clearTimeout(delayTimeout); }; return def; } })(); 

使用示例:

 // optional: set a random delay to all `ajax` calls (between 1s-5s) $.ajax.delay = Math.floor(Math.random() * 5000) + 1000; var myAjax = $.ajax({url:'http://whatever.com/API/1', timeout:5000}) .done(function(){ console.log('done', arguments) }) .fail(function(){ console.log('fail', arguments) }) .always(function(){ console.log('always', arguments) }) // Can abort the ajax call // myAjax.abort();