2013-09-20 129 views
2

好了,所以我有一个非常简单的图像幻灯片这里是jsfiddle停止setTimeout函数

因为你们可以看到它正常工作,当您单击开始。然而,当您单击停止功能不断去这里是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); 
}; 
+0

你调用任何理由'反复setTimeout'而不是调用'setInterval'一次? – Barmar

回答

4

的问题是你的变量的作用域。移动var timer;您的文档准备功能之外,它会工作。当然,这使得它成为一个全球性的,这是不好的。因此,您可能想将StartShow移动到文档就绪功能中。

+0

http://jsfiddle.net/Palestinian/sRn93/2/ – Omar

+0

谢谢大家帮我出 – swsa

2

timer被声明为$(document).ready函数的局部变量,因此它是不是在startShow功能可用。

的解决方案是让timer一个全局变量,或者更好的重新组织你的代码使用关闭。

JS Fiddle Demo

让我解释一下这是怎么回事用一个例子。

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

startShow被分配全局变量timer,但是当你调用clearTimeout你是哪里的局部变量timer被宣布为document.ready(function() {...})内。该局部变量隐藏全局变量。

要么摆脱var timer;声明,要么在0123函数内移动startShow()

+0

谢谢大家帮我出 – swsa