循环遍历一组名称,每隔一段时间采取操作

Loop through a set of names, taking action at interval

本文关键字:一段时间 操作 遍历 一组 循环      更新时间:2023-09-26

在使用JavaScript/jQuery的HTML页面中,我有一个图像文件名数组(arListx)。在该页上,我有一个名为show(pict)的例程,它以某种方式处理图像,然后显示它。

我想通过show(pict)以特定的间隔运行每个图像来模拟幻灯片。

到目前为止,我最好的运气是得到最后要显示的图像(显然,所有图像都通过代码运行,但只有最后显示)。

使用我对5226285 (settimeout-in-a-for-loop and pass- I -as-value)的解释,我得出了如下结论:

function doSetTimeout(i) {
  setTimeout(function() { show(arListx[i]); }, 5000);
}
.
.
.
//[main]
for(i=0; i<arListx.length; i++) {
    doSetTimeout(i);
}
.
.
.
function show(pict) {
    $("#OurPicture").attr('src',pict);
  .
  .
  .
}

我显然做错了什么,欢迎大家多多指教。

您需要使用i*5000逐步设置超时,以便它们显示为0,5000,10000,15000等。你写的东西只是在5秒后把它们都叫了。

function doSetTimeout(i) {
  setTimeout(function() { show(arListx[i]); }, i*5000);
}
.
.
.
//[main]
for(i=0; i<arListx.length; i++) {
    doSetTimeout(i);
}
.
.
.
function show(pict) {
    $("#OurPicture").attr('src',pict);
  .
  .
  .
}