Search code examples
javascriptanimationdelaysetintervalclearinterval

How to modify styles dynamically at set intervals using javascript?


I am trying to dynamically add styles to an element after certain intervals, in order to create an animation effect using javascript alone. I've used setInterval() and am not able to clearInterval/ make it stop. Also, it isn't occurring at the intervals I'm assigning to the method - the animation seems to be occurring every one or two seconds.

Here is the code for what I've tried so far: http://codepen.io/AnkitaSood/pen/jyaqMR?editors=0010

Below is the logic that I need help with -

Object.keys(styles).forEach(function(key) {
    for(index = 0 ; index < styles[key].length; index++) {
      var intervals = setInterval(function(index) {
        elem.style[key] = styles[key][index];
      }, timer[index], index); 
    }
    clearInterval(intervals);
  });

Solution

  • The reason your code is not working is because only last intervals got cleared (your code keep overriding it). But even if you fix it, it wont't work as you expect as the clearInterval may immediately clear the interval even before the changes happen.

    So I'm suggesting setTimeout instead:

    this.animate = function() {
      for(index = 0 ; index < timer.length; index++) {
          setTimeout(function(index) {
            for (var key in styles) {
              elem.style[key] = styles[key][index];
            }
          }, timer[index], index); 
        }
    };