Using SetInterval to add and subtract decimals

This code block runs fine:

let fadeOutWelcome = setInterval(function() {
    if(!welcomeSection.style.opacity) {
      welcomeSection.style.opacity = 1;
    }
    if(welcomeSection.style.opacity > 0) {
      welcomeSection.style.opacity -= 0.1;
      console.log('work dude');
    } else {
      clearInterval(fadeOutWelcome);
    }
  }, 100);  

This code does not:

  let fadeInPortfolio = () => {
  let fadeInPort = setInterval(function() {  
    if(!projects.style.opacity) {
       projects.style.opacity = 0;
    }
    if(projects.style.opacity == 1) {
      clearInterval(fadeInPort);
    } else {
      projects.style.display = 'block';
      projects.style.opacity += 0.1;
      console.log('work man');
    }
  }, 100); 
}
``

the second code block adds 0.1 one time, changes the display to block and then logs work man in an endless loop. any ideas..

Every time setInterval fires it resets projects.style.opacity to zero.

1 Like

Seems obvious enough. Removed that line and it still seems to be only adding the interval once while still logging work man endlessly. its running the block but not the arithmetic.

type or paste code here

let fadeInPortfolio = () => {
  let fadeInPort = setInterval(function() {    
    if(projects.style.opacity == 1) {
      clearInterval(fadeInPort);
    } else {
      projects.style.display = 'block';
      projects.style.opacity += 0.1;
      console.log('work man');
    }
  }, 100); 
}

projects.style.opacity is a string and the first block runs correctly because when you subtract then the string is coerced to a number but in the second block when you add the number is coerced to a string because addition on strings is concatenation. Type coercion is a common source of bugs in javascript.

1 Like

Thanks man. Literally just changed it to projects.style.opacity -= -0.1 and there she goes. Wonder why Javascript types coerce like that based on the operation. Will this solution cause future problems or should i try to tackle using toFixed() and parseInt somehow?

I don’t think it should cause any problems. You just always have to be wary of type coercion with javascript.

1 Like