I'm trying to use getTime to set a timer for an image gallery. When I add an alert during the else block of imageWait() this function works perfectly but without the alert nothing happens. Any ideas why?

milliseconds=null;
galleryLoop();

function galleryLoop(){
    date=new Date();
    startTime=date.getTime();
    milliseconds=5000;
    imageWait();    
}

function imageWait(){
    date=new Date();
    currentTime=date.getTime();
    if(startTime+milliseconds<=currentTime)
        alert('made it')
    else
        imageWait();
}
有帮助吗?

解决方案

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);

其他提示

Why don't you use the setTimeout function for this?

function galleryLoop(){
    setTimeout(5000, imageWait());
}

function imageWait() {
    //Whatever you need to do
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top