Reputation: 1722
I want to display two images which should change every 50 seconds. Each image should be displayed for 120 seconds.
window.onload = function() {
var dir = "0";
setInterval(function () {
var element = document.getElementById("maincontainer");
if(element.style.display == "none") {
if(dir == "1") {
dir = "0";
} else {
dir = "1";
}
loadNewImages(dir);
element.style.display = "block";
} else {
element.style.display = "none";
}
}, 50000);
Some simple HTML code with a div container:
<div id="maincontainer">
<img src="myimage.png" />
</div>
I try to play around with:
setTimeout(function() {
element.style.display = "none";
}
),
120000)
But this did not work.
I need a solution in plain JavaScript. With jQuery I can simply use delay
or other magic.
Can someone give me a hint how to achieve my requirement?
Upvotes: 0
Views: 3148
Reputation: 86220
I recommend using a cycle pattern. Here's a demo (using 1.2 seconds to save you 1.98 minutes).
var images = document.getElementsByTagName("img");
We wrap this in a closure so we can control our i
variable.
(function(){
var i = 0;
The first thing we do in our interval is to hide the current image, which is images[i].
setInterval(function(){
images[i].style.display = "none";
The we check and see if i+1 would be a valid image. You could also write this as images[i+1] != null
. If we can increment it, we do. Otherwise we start back at 0. With two images this toggles between 0 and 1. With 5 images it cycles 0, 1, 2, 3, 4, 0, 1, 2, ...
if (i+1 < images.length) {
i++;
}
else {
i = 0;
}
Our new image is displayed. This will be image[i] when the timer runs again, so it will be hidden.
images[i].style.display = "inline-block";
}, 120000);
})();
Upvotes: 1