当我尝试按照本教程在 JavaScript 中制作旋转横幅时遇到了一个难题。
所有图像都以固定间隔显示setTimeout。后来我想添加一个按钮,允许用户手动切换到横幅上的下一个图像,所以我想我会clearTimeout先停止自动切换的计时器,然后在手动切换后重置它。但是,我很困惑,我必须调用clearTimeout两次才能在重置之前正确停止原始计时器。调用clearTimeout一次无法正确停止计时器。谁能帮我解释一下为什么会这样?我的代码有什么问题吗?以下是部分代码:
//Global Variables
var switchTimeout;
myBanner = new Array("img/chicken.jpg", "img/tiger.jpg", "img/pig.jpg");
var bannerCounter = 0;
//Called after the page is loaded
function switchBanner() {
if (document.images) {
bannerCounter++;
if (bannerCounter == myBanner.length) {
bannerCounter = 0;
}
document.getElementById("banner").src = myBanner[bannerCounter];
switchTimeout = setTimeout("switchBanner()",3000);
}
}
//Called when user hits the button
function manualSwitch() {
//Why do I need to call this twice for it to work?
clearTimeout(switchTimeout);
clearTimeout(switchTimeout);
if (document.images) {
bannerCounter++;
console.log(bannerCounter);
if (bannerCounter == myBanner.length) {
bannerCounter = 0;
}
document.getElementById("banner").src = myBanner[bannerCounter];
//Reset the timer now
switchTimeout = setTimeout("switchBanner()",3000);
}
}
非常感谢您的帮助!