How do I stop an interval in js?

3

Hello, my problem arises when I stop an interval in javascript, because even if I use the ClearInterval it continues printing.

var canvas = document.getElementById('canvas');
 var btnInicia = document.getElementById("inicia");
var btnPara = document.getElementById("parar");

 //setting width and height of the canvas 
 canvas.width = canvasWidth;
 canvas.height = canvasHeight; 

 //Establishing a context to the canvas 
 var ctx = canvas.getContext("2d");

 //Creating an Image object for our character 
 var character = new Image(); 
 var characterStop = new Image();
 //Setting the source to the image file 
 character.src = "imagenes/character.png";
 characterStop.src="imagenes/character.png";
btnInicia.addEventListener("click",
    function(){
        draw();     
        IniciaMono();



    });
btnPara.addEventListener("click",
    function(){
        ctx.clearRect(x,y,width,height);

        ParaMono();
    });

function updateFrame(){
 //Updating the frame index 
 curFrame = ++curFrame % frameCount; 
 //Calculating the x coordinate for spritesheet 
 srcX = curFrame * width; 
}
function draw(){
 //Updating the frame 
 updateFrame();

 ctx.clearRect(x,y,width,height);
 //Drawing the image 
 ctx.drawImage(character,srcX,srcY,width,height,x,y,width,height);
//Intervalo(Funcion que,Tiempo al imprimir)
}

function ParaMono(){
    updateFrame();
    clearInterval(draw);
}

function IniciaMono(){
setInterval(draw , 100);
}
    
asked by Pedro Robles 29.03.2018 в 05:46
source

1 answer

5

The problem is that draw is the name of the callback function that you are using to intervene.

You can do something like this:

let drawInterval;
function IniciaMono(){
    drawInterval = setInterval(draw, 100);
}

function ParaMono() {
    clearInterval(drawInterval);
}
    
answered by 29.03.2018 / 06:10
source