I’m using setInterval
to iterate through some images on a page and hide/show the next in a list after x seconds have passed. Every 30 seconds, I make a GET
request to check for new images from my server. Because the http
request takes about a second, setInterval begins executing the next iteration of my code which causes things to get a little screwy. What would be the best way to fix this issue? Here is a sample of my code:
JavaScript
x
17
17
1
function play(){
2
if(count == 30){
3
sync();
4
//while sync is running (because it takes so long) the play function is called again before the sync operation finishes.
5
}
6
//iterate through the photos hiding and showing them each second.
7
}
8
9
function sync(){
10
//http request that takes about a second to complete and updates images on the page.
11
}
12
window.setInterval(function(){
13
play();
14
currentSeconds++;
15
count++;
16
},1000);
17
Advertisement
Answer
Something like this.
JavaScript
1
21
21
1
function play(){
2
if(count == 30){
3
sync().then(() => setTimeout(play, 1000));
4
} else {
5
setTimeout(play, 1000);
6
}
7
currentSeconds++;
8
count++;
9
}
10
11
function sync(){
12
// Use a promise here.
13
return new Promise((resolve, reject) => {
14
setTimeout(() => {
15
resolve();
16
}, 3000);
17
})
18
//http request that takes about a second to complete and updates images on the page.
19
}
20
21
play();
OR , use a flag and simply return if sync is busy.
JavaScript
1
44
44
1
var syncActive = false;
2
var currentSeconds = 0;
3
var count = 0;
4
5
function play(){
6
console.log('trying to play');
7
if(syncActive) return false;
8
if(count == 30){
9
sync();
10
count = 0;
11
12
}
13
console.log(`could play - count: ${count}`);
14
return true;
15
}
16
17
function sync(){
18
syncActive = true;
19
console.log('syncing');
20
21
// DO LONG TASK
22
sleep(5000).then(() => {
23
// Note this code is in here to siumlate the long run.
24
console.log('completed sync');
25
syncActive = false;
26
});
27
28
29
}
30
31
window.setInterval(function(){
32
if(play()) {
33
console.log('increase counts');
34
currentSeconds++;
35
count++;
36
}
37
},100); //<-- reduced to 100 for demo.
38
39
40
// DUMMY CODE - Just for demo.
41
42
const sleep = (milliseconds) => {
43
return new Promise(resolve => setTimeout(resolve, milliseconds))
44
};