[英]javascript setTimeout fuction,is something wrong with it
我使用 settimeout function,为什么它不起作用。 我只想每 2 秒更改一次图像。 但什么也没发生,它只显示第一张图像,但没有改变。
<script type="text/javascript">
function parta(){
document.getElementById("carimg").src="c1.img";
window.setTimeout(partb,2000);
}
function partb(){
document.getElementById("carimg").src="c2.jpg";
window.setTimeout(partc,2000);
}
function partc(){
document.getElementById("carimg").src="c3.jpg";
window.setTimeout(parta,2000);
}
</script>
您一遍又一遍地声明三个函数,并且从不调用它们中的任何一个。
如果要在三个图像之间切换,请将它们放入一个数组中,并使用setInterval
一次一个元素地通过数组 go :
var images = ['c1.img', 'c2.jpg', 'c3.jpg'];
var imgNum = 0;
function rotateImage() {
document.getElementById("carimg").src= images[imgNum];
imgNum = (imgNum + 1) % images.length;
}
rotateImage();
setInterval(rotateImage, 2000);
如果你想让你的代码接近你现在所拥有的,你只需要改变一些事情:
function parta() {
document.getElementById("carimg").src="c1.img";
window.setTimeout(partb,2000);
}
function partb() {
document.getElementById("carimg").src="c2.jpg";
window.setTimeout(partc,2000);
}
function partc() {
document.getElementById("carimg").src="c3.jpg";
window.setTimeout(parta,2000);
}
parta();
在这种情况下不需要使用while
,因为每个 function 将在 2 秒后相互调用。 但是,您仍然需要启动“循环”,这就是您需要调用parta()
的原因。 此外,在这种情况下使用setInterval
可能更有意义。
您可以在 CodePen 上使用此代码片段: https://codepen.io/yvesgurcan/pen/RwwOawO 。
首先,您不需要使用 while,其次,您错过了函数的括号。
function parta(){ document.getElementById("carimg").src="c1.jpg"; window.setTimeout(partb,2000); } function partb(){ document.getElementById("carimg").src="c2.jpg"; window.setTimeout(partc,2000); } function partc(){ document.getElementById("carimg").src="c3.jpg"; window.setTimeout(parta,2000); } parta();
<img src="" id="carimg">
试试这个
let imageSrc = ['c1.img', 'c2.jpg', 'c3.jpg'];
let imgIndex;
setInterval(()=>{
if(imgIndex == undefined) {
imgIndex = 0;
} else {
if(imgIndex >= imageSrc.length - 1) {
imgIndex = 0;
} else {
imgIndex++;
}
}
document.getElementById("carimg").src = imageSrc[imgIndex];
}, 2000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.