The reason why this works when you add the alert statement to the else clause is that alert is a blocking call meaning JavaScript execution stops when an alert window is created. That said, when the alert statement comes up it allows the wall-clock time to increment (again, there is no JS execution as time in the real world advances) and the if statement is eventually satisfied once the alert is cleared. This also means that if you clear the alert fast enough, there's a chance you'll run into the same problem as before.
What happens ordinarily--without the alert statement--is that the JS engine processes several calls to imageWait during the 5000ms delay and eventually reaches the maximum call-stack size--stack overflow if you will--and throws an error.
The proper solution would be to delay this function using setTimeout:
var galleryTimeout = 0;
function galleryLoop(){
//Process current image
galleryTimeout = setTimeout(galleryLoop, 5000);
}
//Some time later, when done with the gallery
clearTimeout(galleryTimeout);