setInterval重叠DOM更改

问题描述 投票:1回答:1

我正在使用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);
javascript
1个回答
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();

或者,使用标志,如果同步忙,则返回。

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))
};
© www.soinside.com 2019 - 2024. All rights reserved.