swsa
swsa

Reputation: 225

stopping a setTimeout function

Okay so i have a very simple image slide show here it is in jsfiddle

as you guys can see it works fine when you click start. however when you click stop the function keeps on going here is the jquery:

$(document).ready(function() {
    var timer;
    $('img.hidden').hide();
    $('img.top').show();

    $('input').click(function(){
            var value = $('input').attr("value");

    if(value == "start"){

    $(this).attr("value","stop");
    startShow();

    }else if(value == "stop"){
            $(this).attr("value","start");
            alert('stopped');
            clearTimeout(timer);

        }   
    });

 });

 function startShow(){
   var $top = $('img.top').attr("src");
   var $last = $('img').last().attr("src");

   if($top != $last ){

    var $topImg = $('img.top');
    var $nextImg = $('img.top').next();

    $topImg.hide();
    $nextImg.show();

    $topImg.removeClass("top");
    $nextImg.addClass("top");
   }
   else{

    var $topImg = $('img.top');
    var $nextImg = $('img').first();

    $topImg.hide();
    $nextImg.show();

    $topImg.removeClass("top");
    $nextImg.addClass("top");

   }
   timer = setTimeout(function() { startShow(); }, 2000);
};

Upvotes: 2

Views: 3509

Answers (3)

Flight Odyssey
Flight Odyssey

Reputation: 2287

timer is declared as a local variable in the $(document).ready function, therefore it is not available in the startShow function.

The solution is to make timer a global variable, or better yet reorganize your code to use closure.

JS Fiddle Demo

Let me explain what's going on with an example.

function main() {
  var x = 3; // declare a local copy of x, available only in this function
  setValueOfX(); // Try to change the value of x (doesn't work)
  console.log(x); //Prints 3
}

function setValueOfX() {
  x = 12; // You would expect this to change the value of x, but it only changes the value of the global x (window.x), not the local x, so this won't work
}
main();

Upvotes: 2

Barbara Laird
Barbara Laird

Reputation: 12717

The problem is your variable's scope. Move var timer; outside your document ready function and it will work. Of course that makes it a global, which is bad. So you might want to instead move StartShow into your document ready function.

Upvotes: 4

Barmar
Barmar

Reputation: 780724

startShow is assigning the global variable timer, but when you call clearTimeout you're inside the document.ready(function() {...}) where a local variable timer was declared. That local variable shadows the global variable.

Either get rid of the var timer; declaration, or move startShow() inside the ready function.

Upvotes: 2

Related Questions