1

I want to use setTimeout to delay the increment counter in the loop in order to change picture every secs. I try to delay the updatePic() use setTimeout but it doesn't work either. Please help. Thanks.

My JS code:

function picAnimation() {
    //var pic = document.getElementById('pic').src;
    for(i = 2; i < 25; ) {  
        updatePic(i);       
        setTimeout(function() {increment(i);} , 1000);
    }
}

function updatePic(i) {
    if(i > 9) {
        document.getElementById('pic').src = "./animation/0" + i + ".png";
    } else {
        document.getElementById('pic').src = "./animation/00" + i + ".png";
    }
}

function increment(i) {
    i++;
}


picAnimation();

My html code:

<center><img id = "pic" src="./animation/001.png" alt="N/A" width="800" height="300"></center>
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
buzzmind
  • 109
  • 2
  • 10
  • 1
    You are not incrementing your loop variable and so you wind up with an infinite loop. – Scott Marcus May 10 '18 at 17:54
  • You are creating a bunch of items that are all going to execute at one second and you lack increment. I am not sure what your goal is, but I am guessing a for loop is not what you are looking for. – epascarello May 10 '18 at 17:55

3 Answers3

1

A for loop is not the right statement to use in this case. The loop does not wait for setTimeout to finish, calling updateLoop and setTimeout 23 times almost instantly. setTimeout is a function that calls the function in the first argument, after a set amount of milliseconds.

Also, the increment function does not change the value of i; JS copies the data, increments the copy, then discards it. Something like that is possible in C++, but not in JS.

You should instead use setTimeout to call picAnimation.

function picAnimation(i) {
    updatePic(i);
    if (i < 25)
        setTimeout(function() {picAnimation(i + 1)}, 1000);
}
picAnimation(2);
0

I'd use recursion -- not a for-loop.

function doSomething (counter) {
    // Terminal case
    if (counter === 25) {
        return;
    }
    // Do work here

    // Schedule the next.
    setTimeout(doSomething, delay, ++counter)
}

// Then start the process 
doSomething(0);
alex
  • 756
  • 4
  • 12
0

You could write a general-purpose function, then your updater becomes just another use-case.

function loopUntilFalse (delay, fn) {
  if (fn() !== false) setTimeout(loopUntilFalse, delay, delay, fn);
}

var animated = 0;
function picAnimation() {
  if (animated >= 25) return false;
  updatePic(animated);
  animated++;
}

picAnimation();
000
  • 26,951
  • 10
  • 71
  • 101