So I need to have an image alternatively appear and disappear every 2 seconds, I’ve been trying using javascript and I’ve gotten stuck, I feel like it’s something so simple but i can’t work it out, any help is appreciated.
HTML
JavaScript
x
4
1
<body onload="Show()">
2
<div align="center">
3
<img id="image" src="image1.png" height="200" width="200">
4
JAVASCRIPT
JavaScript
1
21
21
1
var Cntr=1
2
3
function Hide()
4
{
5
Cntr++;
6
document.getElementById("image").style.visibility="hidden";
7
if (Cntr==2){
8
setTimeout("Hide", 2000);
9
}
10
}
11
12
function Show()
13
{
14
Cntr--;
15
document.getElementbyId("image").style.visibility="visible";
16
if (Cntr==1) {
17
setTimeout("Show", 2000);
18
}
19
20
}
21
Advertisement
Answer
You need to use callback functions in your setInterval
.
I changed your JavaScript to this:
JavaScript
1
10
10
1
var isHidden = false;
2
3
setInterval(function(){
4
var el = document.getElementById("image");
5
el.style.visibility = isHidden ? "visible" : "hidden";
6
7
// toggle hidden property
8
isHidden = !isHidden;
9
}, 2000);
10
here is a JSFIDDLE as well.