我使用setTimeout来运行幻灯片。我想要按钮来阻止它。标记是:使用clearTimeout的范围问题
<h3> Modest Mouse at Fillmore in Miami <h3>
<div>
<img id="photo" src="http://the305.com/blog/wp-content/uploads/2014/05/modestmouse3.jpg" alt= "Modest Mouse at Fillmore">
<span>•</span>
<span>•</span>
<span>•</span>
</div>
<button onclick="stopShow();">Stop</button>
的JS是:
var aSlideShowPics = ["http://the305.com/blog/wp-content/uploads/2014/05/modestmouse3.jpg",
"http://the305.com/blog/wp-content/uploads/2014/05/modestmoude7.jpg",
"http://the305.com/blog/wp-content/uploads/2014/05/modestmouse8.jpg"
];
// Timer for SlideShow
var i = 0;
function changeSlide() {
var stopShowID;
stopShowID = window.setTimeout(function() {
newPic = aSlideShowPics[i];
$("#photo").attr("src", newPic);
i++;
if (i < aSlideShowPics.length) {
changeSlide(); // recursive call to increment i and change picture in DOM.
} else {
i = 0; // reset loop to keep slideshow going
changeSlide(); // Recursive call on loop end
}
function stopShow() {
window.clearTimeout(stopShowID);
}
}, 3000)
}
changeSlide();
我不断收到上没有stopShow的按钮,点击引用错误。我试过在代码中的几个地方放置clearTimeout函数,但得到相同的错误。也许一组新的眼睛可以看到我的错误。这里是jsfiddle。感谢您的任何意见。
的为什么是超时内stopShow?这是你的问题 – epascarello
我认为这是问题,但当我把它移到changelide以外的全球范围和相同的错误... – alan