Search code examples
javascriptloopscss-animationssettimeout

Javascript animation not showing one after the other


I'm not an expert in javascript and this might be pretty straightforward but I would really appreciate some help. I am trying to show each menu item one after the other with a little animation. Those elements are hidden for another reason so I have to unhide them as well. For the moment all i get is one animation for all the elements:

            for (let i = 1; i < 10; i++) {
                setTimeout(function(){   
                    setTimeout(function(){   
                        document.getElementById('sm-menu-'+i).classList.add('fadeinfrombottom');
                        document.getElementById('sm-menu-'+i).classList.remove('d-none');     
                        }, 100);  
                    }, 700);
            }

Thanks for you help!


Solution

  • The problem with your current code is that all timeout functions starts at the same time

    you can try using different delays like this

    function current() {
    
      console.log('start')
      for (let i = 1; i < 10; i++) {
        setTimeout(() => {
          console.log(i)
        }, 1000)
      }
    }
    
    function newImplementation() {
    
      console.log('start')
      for (let i = 1; i < 10; i++) {
        setTimeout(() => {
          console.log(i)
        }, 1000 * i)
      }
    }
    <div><button id="current" onclick="current()"> Current implementation</div>
    <div><button onclick="newImplementation()"> new implementation</div>