I tried to toggle the setInterval()
function by clicking on an image.
On first click it will start to change the image with a time interval that we set. But after the second click the setInterval()
function is not being stopped (which I wanted), instead the interval reduces. And the interval keep on reducing after each click. Which means it is not toggling properly. Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Learning JavaScript</title>
<script type="text/javascript">
var settimer;
var stop;
function change_timer(){
if(settimer==="on"){
clearInterval(stop);
var settimer="off";
}
else{
var stop=setInterval('change()',2000);
var settimer="on";
}
}
function change(){
var img=document.getElementById('browser');
if(img.src==="http://localhost:8383/JavaScript/firefox.jpg")
{img.src="chrome.jpg";}
else{img.src="firefox.jpg";}
}
</script>
</head>
<body>
<img src="firefox.jpg" alt='browser' id='browser' onclick='change_timer();'>
<p>Click on image to set timer on or off</p>
</body>
</html>