Why toggling a setInterval() which changes a image source is only decreasing the interval time after each toggle?

时间:2017-06-15 10:36:56

标签: javascript html

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>

2 个答案:

答案 0 :(得分:1)

以下是您的问题的工作示例

&#13;
&#13;
var settimernow="off";
var stop;

function change_timer(){
   if(settimernow==="on"){
      clearInterval(stop);                 
      settimernow="off";
   }
   else{
      stop=setInterval('change()',2000);
      settimernow="on";
       }
}
        
function change(){
      var img=document.getElementById('browser');             
      if(img.src==="https://www.w3schools.com/css/trolltunga.jpg")         {
        img.src="http://hdwallpaperfun.com/wp-content/uploads/2015/07/Big-Waves-Fantasy-Image-HD.jpg";
      }    
      else
      {
          img.src="https://www.w3schools.com/css/trolltunga.jpg";
      }
}
&#13;
<body>
<img src="http://hdwallpaperfun.com/wp-content/uploads/2015/07/Big-Waves-Fantasy-Image-HD.jpg" alt='browser' id='browser' width="100px" height="100px" onclick='change_timer();'>
<p>Click on image to set timer on or off</p> 
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这一行

var stop=setInterval('change()',2000);

...创建一个新的,本地范围的变量stop,而不是分配给您在外部范围中创建的变量,因此当您稍后运行clearInterval(stop)时(在新的&#39;实例& #39;具有新范围的功能)您没有清除之前创建的间隔。

settimer变量也是如此。

只需从var函数中的这些行中删除change_timer()关键字,它就可以正常运行。