[英]Change image and link every 5 seconds
I am using following code to change image and link every 5 seconds but the second image https://img2.png stays for 10 seconds - what am I missing?我正在使用以下代码每 5 秒更改一次图像和链接,但第二张图像https://img2.png停留 10 秒 - 我错过了什么?
<script>
var links = ["https://website1.com","https://website2.com"];
var images = ["https://img1.jpg","https://img2.png"];
var i = 0;
var renew = setInterval(function(){
if(links.length == i){
i = 0;
}
else {
document.getElementById("bannerImage").src = images[i], style="width:100%; height: auto;";
document.getElementById("bannerLink").href = links[i], target="_blank";
i++;
}
},5000);
</script>
<a id="bannerLink" target="_blank" href="https://website1.com" onclick="void window.open(this.href);
return false;">
<img id="bannerImage" style="width:100%; height: auto;" src="https://img1.jpg">
Let's go through the logic:让我们来看看逻辑:
var i = 0;
The counter i
is set to 0
计数器
i
设置为0
if(links.length == i){
i = 0;
} else {
document.getElementById("bannerImage").src = images[i], style="width:100%; height: auto;";
document.getElementById("bannerLink").href = links[i], target="_blank";
i++;
}
if links.length == i
, set i = 0
.如果
links.length == i
,则设置i = 0
。 links.length
in this case is 2
, so the condition fails.本例中的
links.length
为2
,因此条件失败。
This means the following case is now executed:这意味着现在执行以下案例:
document.getElementById("bannerImage").src = images[i], style="width:100%; height: auto;";
document.getElementById("bannerLink").href = links[i], target="_blank";
i++;
Hence i
is now 1. The setInterval
function now waits 5 seconds.因此
i
现在是 1。 setInterval
函数现在等待 5 秒。
This is repeated and then i
is set to 2
.重复此操作,然后将
i
设置为2
。 The setInterval
function now waits 5 seconds. setInterval
函数现在等待 5 秒。
We then go into the third iteration.然后我们进入第三次迭代。 In this iteration,
links.length == i
is TRUE
and i
is set to 0
.在此迭代中,
links.length == i
为TRUE
并且i
设置为0
。 However, nothing else happens (the if statement does not change the picture in this iteration) and therefore the setInterval
function waits 5 seconds before continuing the loop.但是,没有其他任何事情发生(if 语句不会更改此迭代中的图片),因此
setInterval
函数在继续循环之前等待 5 秒。 That's where your extra 5 seconds come from.这就是你额外 5 秒的来源。 The picture is not changed in the third loop, but the
setInterval
function does wait for 5 seconds.在第三次循环中图片没有改变,但是
setInterval
函数确实等待了 5 秒。
If you simply want to run this code forever and change the picture every 5 seconds, this is how you could do it:如果您只想永远运行此代码并每 5 秒更改一次图片,您可以这样做:
setInterval(function(){
// Always change the picture first
document.getElementById("bannerImage").src = images[i], style="width:100%; height: auto;";
document.getElementById("bannerLink").href = links[i], target="_blank";
// Always increment the counter
i++;
// Reset counter if equal to length of array
if (i == links.length){
i = 0;
}
},5000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.