Search code examples
javascriptfor-looptimedelay

How do you slow down the execution of a for loop in JavaScript?


I am making a basic image slider (press the next/prev button and the picture changes). I am also trying to implement a very simple fade effect; to do this I have a for loop which changes the class of the image, cycling through classes that change the opacity. The code works fine and does what I want it to do, but the for loop executes so quickly that you don't notice the change in opacity. I have looked all over and everywhere people are mentioning setTimeout, but that only causes a delayed start of a function.. I just want to slow my for loop so you can visually notice each iteration.

function nextphoto(){

    for(var x = 0; x < 5; x++){
        photo.className = fade[x];
    }

    i++;
    if(i>19){
    i=0;
    }

    photo.src = image[i];

    for(var y = 4; y >= 0; y--){
        photo.className = fade[y];
    }
}

Solution

  • You might be misunderstanding the concept of synchronous code execution. All of your code has to finish running before anything can be updated or "rendered" to the screen. So your for loop will run until it's done, then the screen will update, but it will of course only have the final view of the image to render.

    You should either trigger a CSS transform, by dynamically adding a class to the element via javascript, or if you were desperate to do it all in code, had some reason not to use CSS, and do not want to write a custom per frame animation system, or use a library, then inside each iteration of the for loop, fire an asynchronous function that will update at a later and later time, outside of the current synchronous for loop code.

    ie:

    var aThing;
    for(var i = 0; i < someNumber; i++){
      setTimeout(function(){
        aThing.someValue = aThing.someValue * .9;
      }, 500 * i);
    }