Andre FIlipe Andre FIlipe - 6 months ago 19
HTML Question

Reset SetInterval to repeat the function on another ID

im having trouble reseting setInterval() on 2 functions, they are suposed to be reused by the affected Ids

Heres the javascript:

//Fuction Fade out
function fadeOut(elem, speed) {

if(!elem.style.opacity)
{
elem.style.opacity = 1;
}

if(elem.style.opacity>=1){
setInterval(function(){
if(elem.style.opacity >=0){
elem.style.opacity = parseFloat(elem.style.opacity) - 0.03;}
}, speed /50);
if(elem.style.opacity >=1){
clearInterval(0);

}
}

}


//Função fade in
function fadeIn(elem, speed) {

if(!elem.style.opacity)
{
elem.style.opacity = 0;
}

/*var timerId=*/
if(elem.style.opacity<=0){
setInterval(function(){
if(elem.style.opacity <=1){
elem.style.opacity = parseFloat(elem.style.opacity) + 0.03;}
}, speed /50);
}
/*if(elem.style.opacity >="1"){
clearInterval(timerId);
return;} */
}


I have tried a while to fix the problem, but it didn't help, when i implement the third "if" on the fadeout function, the opacity valor goes down, but instead of going back to 0, it goes to 0,99. What can I do?

Answer

The clearInterval needs the name of the interval to clear I think, you need to name put you interval in a variable like this :

var myInterval = setInterval(function(){
  if(elem.style.opacity >=0){
    elem.style.opacity = parseFloat(elem.style.opacity) - 0.03;
  } 
}, speed /50);

then you ca clear it like this :

clearInterval(myInterval);
Comments