anon
anon

Reputation: 77

jQuery + setTimeout() + clearTimeout() not working in IE7 & 8

This works in Firefox and Chrome but not in IE.

In Internet Explorer the timers are not being cleared out and it appears each time update_slideshow() is called a new timer is created.

// slideshow params 
var currentSlide = 1;
var numSlides = 4;
var pause = false;

function pause_show(bool){
    pause = bool;
}

// transitions the slides 
function update_slideshow(slide){
    if(slide > numSlides) slide = 1;

    //is user tyring to pause/play this slide
    if(currentSlide == slide){
        switch(pause){
            case false:
                $("#ssbut" + slide.toString()).removeClass('pause').addClass('play');
                pause = true;
            break;

            case true:
                $("#ssbut" + slide.toString()).removeClass('play').addClass('pause');
                pause = false;
            break;
        }
    }else{ //user clicked on a button other than the current slide's
        clearTimeout(slideTimer);
        function complete() {
            $("#slide" + slide.toString()).fadeIn(500, "linear");
            if(!pause)  
                $("#ssbut" + slide.toString()).removeClass('inactive').addClass('pause');
            else
                $("#ssbut" + slide.toString()).removeClass('inactive').addClass('play');
        }   
        $("#ssbut" + currentSlide.toString()).removeClass('play').addClass('inactive');
        $("#slide" + currentSlide.toString()).fadeOut(300, "linear", complete);

        currentSlide = slide;
        if (typeof(slideTimer) != 'undefined') clearTimeout(slideTimer);
        slideTimer = setTimeout("slideshow()",4000);
    }
}

function slideshow(){
    if (typeof(slideTimer) != 'undefined') clearTimeout(slideTimer);
    if(!pause){
        update_slideshow(currentSlide + 1);
    }
    slideTimer = setTimeout("slideshow()",4000);
}
var slideTimer = setTimeout("slideshow()",4000);

Upvotes: 1

Views: 5155

Answers (1)

Ken Redler
Ken Redler

Reputation: 23943

You might try using setTimeout with a function reference instead of a string. Change this:

setTimeout("slideshow()",4000);

To this:

setTimeout( slideshow, 4000 );

As a side note, you might consider simplifying some code. You only have two states for pause, so this:

switch(pause){
  case false:
    $("#ssbut" + slide.toString()).removeClass('pause').addClass('play');
    pause = true;
    break;
  case true:
    $("#ssbut" + slide.toString()).removeClass('play').addClass('pause');
    pause = false;
    break;
 }

...can be rewritten something like this:

$('#ssbut' + slide.toString()).toggleClass('pause play', pause);
pause = !pause;


Update: Noticed that the OP was inadvertently recursing in the slideShow function:

function slideshow(){
  // stuff
  slideTimer = setTimeout("slideshow()",4000); // -> now there's your problem
}

Removing that line solves the problem.

Upvotes: 3

Related Questions