我正在使用setInterval
遍历页面上的某些图像,并在x秒过去之后隐藏/显示列表中的下一个图像。每隔30秒,我会发出一个GET
请求,以检查服务器中是否有新图像。因为http
请求大约需要一秒钟,所以setInterval开始执行我的代码的下一次迭代,这会使事情变得有些棘手。解决此问题的最佳方法是什么?这是我的代码示例:
function play(){
if(count == 30){
sync();
//while sync is running (because it takes so long) the play function is called again before the sync operation finishes.
}
//iterate through the photos hiding and showing them each second.
}
function sync(){
//http request that takes about a second to complete and updates images on the page.
}
window.setInterval(function(){
play();
currentSeconds++;
count++;
},1000);
答案 0 :(得分:1)
这样的事情。
function play(){
if(count == 30){
sync().then(() => setTimeout(play, 1000));
} else {
setTimeout(play, 1000);
}
currentSeconds++;
count++;
}
function sync(){
// Use a promise here.
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 3000);
})
//http request that takes about a second to complete and updates images on the page.
}
play();
OR,使用一个标志,如果同步很忙就简单地返回。
var syncActive = false;
var currentSeconds = 0;
var count = 0;
function play(){
console.log('trying to play');
if(syncActive) return false;
if(count == 30){
sync();
count = 0;
}
console.log(`could play - count: ${count}`);
return true;
}
function sync(){
syncActive = true;
console.log('syncing');
// DO LONG TASK
sleep(5000).then(() => {
// Note this code is in here to siumlate the long run.
console.log('completed sync');
syncActive = false;
});
}
window.setInterval(function(){
if(play()) {
console.log('increase counts');
currentSeconds++;
count++;
}
},100); //<-- reduced to 100 for demo.
// DUMMY CODE - Just for demo.
const sleep = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds))
};