脚本setTimeout/setInterval

2022-04-17 00:00:00 javascript slideshow

正在尝试为测试网页制作一个小幻灯片。我搞不懂为什么这段代码不能工作(我对Java不是很有经验,我主要是在处理Java,Java脚本非常令人沮丧)。另外,我想补充的是,它确实开始运行,它将在几秒钟后切换到第三张图片,然后它停止,永远不再切换。

var backgroundElement = document.getElementById("innerContent");
var minibarImage1 = document.getElementById("pic1");
var minibarImage2 = document.getElementById("pic2");
var minibarImage3 = document.getElementById("pic3");


minibarImage1.onmouseover = function(){
    backgroundElement.style.backgroundImage="url('images/frontpage/maintenance_01.jpg')";
};

minibarImage2.onmouseover = function() {
    backgroundElement.style.backgroundImage ="url('images/frontpage/natural_steps_01.jpg')";
};

minibarImage3.onmouseover = function() {
    backgroundElement.style.backgroundImage = "url('images/frontpage/twnshp_bdg_01b.jpg')";
};

function slideshow() {
setTimeout(function(){backgroundElement.style.backgroundImage= "url('images/frontpage/maintenance_01.jpg')";}, 2000);
setTimeout(function(){backgroundElement.style.backgroundImage = "url('images/frontpage/natural_steps_01.jpg')";}, 2000);
setTimeout(function(){backgroundElement.style.backgroundImage = "url('images/frontpage/twnshp_bdg_01b.jpg')";}, 2000);
}   


 window.onload = setInterval(function(){slideshow();}, 8000);

解决方案

我已经指出:

window.onload = setInterval(function(){slideshow();}, 8000);

应该是这样的:

window.onload = function(){
    setInterval(function(){slideshow();}, 8000);
}

window.onload存储函数。setInterval返回该间隔的ID,以便您可以选择停止它。

此外,setTimeout不会暂停程序的执行。因此,您对setTimeout的连续调用都是同时执行的--在调用slideshow两秒钟后执行。

您可以尝试嵌套回调函数,如下所示:

function slideshow (){

    setTimeout(function(){
        backgroundElement.style.backgroundImage= "url('images/frontpage/maintenance_01.jpg')";
        setTimeout(function(){
            backgroundElement.style.backgroundImage = "url('images/frontpage/natural_steps_01.jpg')";
            setTimeout(function(){
                backgroundElement.style.backgroundImage = "url('images/frontpage/twnshp_bdg_01b.jpg')";
                slideshow();
            },  2000);
        },  2000);
    },  2000);
}

slideshow();

可能有一种更优雅的方法,但您明白了。

编辑:

这样可能更优雅:

function slideshow() {
    setTimeout (function(){backgroundElement.style.backgroundImage = "uri";}, 2000);
    setTimeout (function(){backgroundElement.style.backgroundImage = "uri";}, 4000);
    setTimeout (function(){backgroundElement.style.backgroundImage = "uri";}, 6000);
    setTimeout (slideshow, 8000);
}   

将秒替换为2。您甚至可以通过添加URL和时间步长参数数组来使幻灯片功能更加模块化,以便您可以在一组URL上迭代setTimeout函数。

有点像这样(伪代码)

function slideshow (urls, timestep){
    var i = 0;
    for (; urls[i]; i++)
        setTimeout (function(){ backgro... = urls[i];}, timestep * i);

    setTimeout (slideshow, timestep * i);
}

slideshow (["url1", "url2", "url3"], 2000);

相关文章