我有以下脚本。
function slideShow1(){
document.getElementById('dynimg').src="Other/noctis.jpg";
var timer1 = setTimeout(slideShow2(),5000);
}
function slideShow2(){
document.getElementById('dynimg').src="Other/retriever.jpg";
var timer2 = setTimeout(slideShow3(),5000);
}
function slideShow3(){
document.getElementById('dynimg').src="Other/miningop2.jpg";
var timer3 = setTimeout(slideShow1(),5000);
}
这很粗糙,我知道...而且它也不起作用。这个想法是让每个函数在给定时间段后触发下一个函数,因此创建一个幻灯片,其中和 img 重复更改。我正在尝试使用 body onload="slideShow1()"
最佳答案
那些括号导致您的函数立即执行。
setTimeout(<b>slideShow2()</b>, 5000);
因此,您认为您正在将您的函数传递给setTimeout
,但实际上您正在执行您的函数并传递它的返回值(在本例中为未定义
)。
因此,您的函数会立即被调用,并且 setTimout
五秒后没有任何内容可执行。
只需删除括号:
function slideShow1(){
document.getElementById('dynimg').src = "Other/noctis.jpg";
setTimeout(slideShow2, 5000);
}
function slideShow2(){
document.getElementById('dynimg').src = "Other/retriever.jpg";
setTimeout(slideShow3, 5000);
}
function slideShow3(){
document.getElementById('dynimg').src = "Other/miningop2.jpg";
setTimeout(slideShow1, 5000);
}
关于javascript - “循环”JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17579031/