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
<body onload="Show()"> <div align="center"> <img id="image" src="image1.png" height="200" width="200">
JAVASCRIPT
var Cntr=1
function Hide()
{
Cntr++;
document.getElementById("image").style.visibility="hidden";
if (Cntr==2){
setTimeout("Hide", 2000);
}
}
function Show()
{
Cntr--;
document.getElementbyId("image").style.visibility="visible";
if (Cntr==1) {
setTimeout("Show", 2000);
}
}
Advertisement
Answer
You need to use callback functions in your setInterval.
I changed your JavaScript to this:
var isHidden = false;
setInterval(function(){
var el = document.getElementById("image");
el.style.visibility = isHidden ? "visible" : "hidden";
// toggle hidden property
isHidden = !isHidden;
}, 2000);
here is a JSFIDDLE as well.