Search code examples
javascriptcountersetintervalclearinterval

clearInterval not working after 6 time setInterval


I want to change an image 6 times to create the illusion of a dice changing the number of dots (a simple animation). But the images don't stop after the 6 time. I think the clearInterval is not working! don't know why

   var d = [  "images/dado1.svg",
              "images/dado2.svg",
              "images/dado3.svg",
              "images/dado4.svg",
              "images/dado5.svg",
              "images/dado6.svg",
              ];

window.onload = function (){
                dado.onclick = move;
            }

   function move() {

                 var md = setInterval(mudaDado,500);

                }


    function mudaDado(){

      dado.setAttribute("src",d[time]);

      time++;

      if(time===6){
      clearInterval(md);

      }

    }

Solution

  • Assign md to global variable:-

    var md;
     var d = [  "images/dado1.svg",
                  "images/dado2.svg",
                  "images/dado3.svg",
                  "images/dado4.svg",
                  "images/dado5.svg",
                  "images/dado6.svg",
                  ];
    
    window.onload = function (){
                    dado.onclick = move;
                }
    
       function move() {
    
                     md = setInterval(mudaDado,500);
    
                    }
    
    
        function mudaDado(){
    
          dado.setAttribute("src",d[time]);
    
          time++;
    
          if(time===6){
          clearInterval(md);
    
          }
    
        }