Roelof van den Berg
Roelof van den Berg

Reputation: 100

How to proper use setTimeout with IE?

For a mockup-webpage used for research on interaction on websites, I created a mockup message-stream using JavaScript. This message stream should show images at pre-set intervals. In Chrome, this code posts the images below one another, at the pre-set intervals. In IE, only the first image is shown. I have already removed the passing of parameters in the window.setTimeout method, but am lost as to what else I need to do to satisfy IE. What else should I do to make all images appear in the pre-set intervals?

My script-section has several global variables:

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

The following functions are present:

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;

Upvotes: 0

Views: 252

Answers (1)

Jim W
Jim W

Reputation: 5016

You can use setInterval instead of repeatedly calling setTimeout, setInterval repeats until you call clearInterval.

Also as noted in the comments, document.writeln is from a different decade ;) You can modify the DOM directly now.

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]);

with this HTML

<div id='holder'>

</div>

Running demo http://jsfiddle.net/W7QXH/4/

Upvotes: 1

Related Questions