[英]Why do I need to call clearTimeout twice to reset setTimeout
我在尝试按照本教程在 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);
}
}
非常感谢您的帮助!
感谢大家对这个问题发表评论。
我只是再次查看了代码,并尝试使用罗马数字而不是 jsfiddle 上的图像编写它的另一个版本:
https://jsfiddle.net/ztk0s3p5/
显然,我只需要调用clearTimeOut()
一次即可停止上述版本中的自动切换计时器。 所以我之前遇到的问题在于我原始代码的其他部分。 现在我确信运行clearTimeout()
应该可以完成工作。 它没有出现在我的原始代码中是由于其他一些错误。 再次感谢!
我对此进行了测试,似乎只调用一次就可以正常工作,也就是说,这似乎更适合使用setInterval()
而不是setTimeout()
。 也减少了一些不必要的代码重复。
请参阅仅使用文本而不是替换img
的source
的示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="banner"> </div>
<button onclick="changeAndTriggerInterval()" id="bannerSwitcher">Switch Banner</button>
<script>
let intervalIdentifier = 0;
let bannerCounter = 0;
myBanner = new Array("img/chicken.jpg", "img/tiger.jpg", "img/pig.jpg");
// Called when user hits the button and on initial page load
function changeAndTriggerInterval() {
changeBanner();
resetBannerChanger();
}
function resetBannerChanger() {
if (intervalIdentifier > 0) {
clearInterval(intervalIdentifier);
}
intervalIdentifier = setInterval(changeBanner, 3000);
}
function changeBanner() {
// Change before updating counter to start from index 0
document.getElementById("banner").innerText = myBanner[bannerCounter];
bannerCounter++;
if (bannerCounter == myBanner.length) {
bannerCounter = 0;
}
}
window.onload = changeAndTriggerInterval;
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.