Question

Here is a "why does this work" instead of "why does this NOT work?" The movePic function updates coordinates for a couple images, and changes images as needed, then calls setTimeOut(movePic, delay). So the movePic function is called WITHIN the mnovePic function.

  1. Why does this not make an endless recursion of functions inside of functions?

  2. If the answer to #1 is that when setTimeOut calls movePic, it also first breaks out of movePic, how does the actual moving of the images, that comes AFTER setTimeOut, ever execute?

The complete page is at www.salemharvest.org. The function is:

function movePic ()  {
left1 += movement;
left2 += movement;
if (left1 > 500)  { //  photo1 disappears over right edge
  left1 = -510; // photo1 goes to  500 left of window
  left2=-510;  // photo2 goes to START of window 
  j=j+1;
  if (j > (p - 1)) j = 0;
  document.images.animated1.src = preLoad[j].src; // switches to photo
  }
else if (left1==0)  { // photo1 fully in window
  left2 =-1010; // photo2 goes to 510 ABSOLUTE to left of window
  j=j+1;
  if (j > (p - 1)) j = 0; 
  document.images.animated2.src = preLoad[j].src; // switches the photo
  }
setTimeout (movePic, delay);
photo1.style.left = left1 + "px"; 
photo2.style.left = left2 + "px"; 
} // end of movePic function
Was it helpful?

Solution

setTimeout schedules the function to be called some time later. It does not affect, and in fact has nothing to do with, the code executing in the current call stack.

By the time the setTimeout callback runs, the previous call already finished; it is not on the call stack.

Therefore, you don't get a stack overflow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top