JavaScript代码有什么问题?

JavaScript代码有什么问题?,javascript,html,Javascript,Html,我正在为自己做一个时间杀手项目,作为等待论坛帖子的一种方式 var factsArray = ['MIT has created a 3D version of Scratch, called StarLogo', 'Duck echos DO quack', 'Ostriches never stick their head in the sand', 'The cigarrete lighter was invented before the match'] var i = 0; funct

我正在为自己做一个时间杀手项目,作为等待论坛帖子的一种方式

var factsArray = ['MIT has created a 3D version of Scratch, called StarLogo', 'Duck echos DO quack', 'Ostriches never stick their head in the sand', 'The cigarrete lighter was invented before the match']
var i = 0;
function start() {
     while (i < 20) {
          setTimeout(function(){document.getElementById('content').innerHTML = factsArray[Math.floor(Math.random() * factsArray.length)];}, 3000);
          i = i + 1;
     }
     setTimeout(function(){document.getElementById('content').innerHTML = "Sixty seconds are up! Go and post!";}, 3000);
}
这是我的密码;到目前为止,它将只显示数组中的一个项,并在那里停止

我想要它做的是每3秒显示一个来自我的factsArray的事实,直到60秒过去,然后它将显示60秒结束!去投递吧

为什么我的代码只显示一个事实,而不是每3秒显示一个?

setTimeout是准异步的,此代码几乎在同一时间添加20个超时,因此它们也在同一时间结束。如果尚未达到总超时,则只需设置一个超时,然后在超时的回调中启动下一个超时。同样,如果已达到总超时,则应添加最后一条语句


您还可以使用setInterval和clearInterval来实现这一点。

我认为您需要执行3000*isetTimeout不会暂停脚本。请改进您的标题和说明。您确定它只显示阵列中的一个项目吗?或者你的超时都是同时执行的,你看到了最终的结果吗?不确定为什么会被搁置,似乎他想每3秒公布一个事实,持续60秒。看起来他没有做任何编辑,对我来说也很清楚。@Jordan-可能是因为代码本身工作正常,毫无疑问。