Answers:
正如其他人指出的那样,setInterval和setTimeout可以解决问题。我想强调一点我从Paul Irish的精彩视频中学到的更先进的技术:http : //paulirish.com/2010/10-things-i-learned-from-the-jquery-source/
对于可能花费比重复间隔更长的周期性任务(例如,慢速连接上的HTTP请求),最好不要使用setInterval()
。如果第一个请求尚未完成,而您又启动了另一个请求,则可能会遇到以下情况:您有多个请求占用了共享资源并且彼此挨饿。通过等待安排下一个请求,直到最后一个请求完成为止,可以避免此问题:
// Use a named immediately-invoked function expression.
(function worker() {
$.get('ajax/test.html', function(data) {
// Now that we've completed the request schedule the next one.
$('.result').html(data);
setTimeout(worker, 5000);
});
})();
为简单起见,我使用成功回调进行调度。不利的一面是,一个失败的请求将停止更新。为了避免这种情况,您可以使用完整的回调:
(function worker() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 5000);
}
});
})();
是的,您可以使用JavaScript setTimeout()
方法或setInterval()
方法来调用您要运行的代码。使用setTimeout的方法如下:
function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}
$(document).ready(function() {
// run the first time; all subsequent calls will take care of themselves
setTimeout(executeQuery, 5000);
});
我尝试了以下代码,
function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}
$(document).ready(function() {
// run the first time; all subsequent calls will take care of themselves
setTimeout(executeQuery, 5000);
});
在指定的时间间隔内,此操作未按预期工作,页面未完全加载,并且连续调用了该函数。最好在下面的单独函数中进行setTimeout(executeQuery, 5000);
外部调用executeQuery()
,
function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
updateCall();
}
function updateCall(){
setTimeout(function(){executeQuery()}, 5000);
}
$(document).ready(function() {
executeQuery();
});
这完全符合预期。