如何在IE中正确使用setTimeout?

时间:2014-03-27 01:50:53

标签: javascript internet-explorer google-chrome

对于用于研究网站上交互的模型网页,我使用JavaScript创建了一个模型消息流。此消息流应以预先设定的间隔显示图像。在Chrome中,此代码以预设的时间间隔将图像发布在彼此之下。在IE中,仅显示第一个图像。我已经在window.setTimeout方法中删除了参数的传递,但是为了满足IE我还需要做什么。我还应该做些什么来使所有图像以预先设定的间隔出现?

我的脚本部分有几个全局变量:

var updateinterval = 400; // a multiplier (integer) used to 
var scrollinterval = 5; // an interval (integer) to wait before scrolling
var point; // integer used to prevent using parameters in window.setTimeout
var interval = [0, 10, 40]; // array of integers creating diversity in intervals
var images = ["r1", "a1", "r2"];// array of strings referring to images to show

存在以下功能:

function trypost(){
  point = point + 1;
  if(point < interval.length){
    //write the required image
    document.writeln("<img src='images/"+images[point]+".png'/><br/>"); 
    //time scroll to bottom
    var stb = window.setTimeout(scrollToBottom, scrollinterval);
    //time next post
    var nextupdate = interval[point]*updateinterval;
    var tp = window.setTimeout(trypost, nextupdate);
  }
}

function scrollToBottom(){
  window.scrollBy(0,document.body.scrollHeight);
}

function startpost(){
  point = -1;
  trypost();
}

window.onload = startpost;

1 个答案:

答案 0 :(得分:1)

您可以使用setInterval而不是重复调用setTimeout,setInterval重复,直到您调用clearInterval。

同样如评论中所述,document.writeln来自不同的十年;) 您现在可以直接修改DOM。

var i=0;
var interval = [0, 10, 400, 10, 1000];
var images = [
  "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRTiW-7zqLiG1DNq4Tmt6x4j1iBc0FZRBpyYZtIXgDzUy_NHwTv",
    "http://img2.wikia.nocookie.net/__cb20120327004334/mrmen/images/a/a0/MrMean.gif",
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRTiW-7zqLiG1DNq4Tmt6x4j1iBc0FZRBpyYZtIXgDzUy_NHwTv",
    "http://img2.wikia.nocookie.net/__cb20120327004334/mrmen/images/a/a0/MrMean.gif",
    "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRTiW-7zqLiG1DNq4Tmt6x4j1iBc0FZRBpyYZtIXgDzUy_NHwTv"
];


for(var i=0; i<interval.length;i++)
var timer = setTimeout(function(img){
    var newImg = document.createElement("IMG");
    newImg.src = img;
    document.getElementById('holder').appendChild(newImg);

}, interval[i], images[i]);

使用此HTML

<div id='holder'>

</div>

运行演示 http://jsfiddle.net/W7QXH/4/