'循环'JavaScript函数

'Looping' JavaScript functions

本文关键字:函数 循环 JavaScript      更新时间:2023-09-26

我有下面的脚本。

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(slideShow2(), 5000);

因此,您认为您正在将函数传递给setTimeout,但实际上正在执行函数并传递其返回值(在本例中为undefined)。

因此,您的函数会立即被调用,而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);
}