问题描述
我有以下$ .each遍历一个对象.每5秒钟调用一次get_file()函数.无论如何,是否包含暂停和继续"选项.这样,如果我单击暂停",数据的加载将停止.当然,当我单击恢复"按钮时,它会从中断处重新启动.
I have the following $.each which loops through an object. Every 5 seconds the get_file() function is called. Is there anyway to include a Pause and Resume option. So that if I click Pause the loading of the data stops. And of course when I click a Resume button it starts up again from where it left off.
希望有人可以提供帮助.
Hope someone can help.
$.each(obj, function (i, v) {
setTimeout(function () {
file = v.new_file;
var timeline_date = moment(v.last_modified_date).format("dddd, MMMM Do YYYY, h:mm:ss a");
bHover = 0; //re-highlight links
$(".timeline_msg").html(timeline_date);
get_file(file);
}, 5000 * (i + 1));
});
推荐答案
对所有计时器进行排列,因此可以在单击暂停按钮时清除它们.使用全局变量跟踪要加载的文件列表中的文件数量.然后,您可以从上次中断的地方继续.
Make an array of all the timers, so you can clear them when the pause button is clicked. Use a global variable to keep track of how far you are through the list of files to load. Then you can resume from where you left off.
var curfile = 0;
var load_file_timers;
function load_files() {
load_file_timers = obj.map(function(v, i) {
if (i < curfile) {
return null;
} else {
return setTimeout(function() {
var file = v.newfile;
var timeline_date = moment(v.last_modified_date).format("dddd, MMMM Do YYYY, h:mm:ss a");
bHover = 0; //re-highlight links
$(".timeline_msg").html(timeline_date);
get_file(file);
curfile++;
}, 5000 * (i - curfile + 1));
}
});
}
load_files();
$("#pause").click(function() {
$.each(load_file_timers, function(i, timer) {
if (timer) {
clearTimeout(timer);
}
});
});
$("#resume").click(load_files);
这篇关于暂停和循环恢复setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!