javascript - Why won't this clearInterval work? -


i'm making race 2 images move right random number of px's won't stop clear interval, alert "stop" works. i'm using red , green picture changing z-indexes stoplight user start , stop race.

<script type="text/javascript">  var ship = 0; var ufo = 0;  function random() {      var rand = math.floor((math.random() * 15) + 1);     var rand2 = math.floor((math.random() * 15) + 1);      ship = ship + rand;     ufo = ufo + rand2;      document.getelementbyid("ufo").style.left = ufo + 'px';     document.getelementbyid("spaceship").style.left = ship + 'px';   }  function start() {     if(document.getelementbyid("red").style.zindex == 1)     {         document.getelementbyid("red").style.zindex = "0";         alert("go");         var timer = setinterval(function() {random()},1000);          }     else     {         document.getelementbyid("green").style.zindex = "0";         document.getelementbyid("red").style.zindex = "1";         clearinterval(timer);         alert("stop");       }  }  </script> 

because var timer exists within if statement. need move outside of start() function, this:

var timer;  function start() {     if(document.getelementbyid("red").style.zindex == 1)     {         document.getelementbyid("red").style.zindex = "0";         alert("go");         timer = setinterval(function() {random()},1000);         }     else     {         document.getelementbyid("green").style.zindex = "0";         document.getelementbyid("red").style.zindex = "1";         clearinterval(timer);         alert("stop");     } } 

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -