scoopzilla
scoopzilla

Reputation: 883

Javascript image timer does not seem to be functioning properly

This does not seem to be functioning properly:

var images = [];
images.push({src: "http://www.mountsinaiparks.org/digital-yahrzeit/wp-content/themes/yahrzeit-theme/Candle_images/Candle01.gif", timeout: 3600000});
images.push({src: "http://www.mountsinaiparks.org/digital-yahrzeit/wp-content/themes/yahrzeit-theme/Candle_images/Candle02.gif", timeout: 16560000});
images.push({src: "http://www.mountsinaiparks.org/digital-yahrzeit/wp-content/themes/yahrzeit-theme/Candle_images/Candle03.gif", timeout: 16560000});
images.push({src: "http://www.mountsinaiparks.org/digital-yahrzeit/wp-content/themes/yahrzeit-theme/Candle_images/Candle04.gif", timeout: 16560000});
images.push({src: "http://www.mountsinaiparks.org/digital-yahrzeit/wp-content/themes/yahrzeit-theme/Candle_images/Candle05.gif", timeout: 16560000});
images.push({src: "http://www.mountsinaiparks.org/digital-yahrzeit/wp-content/themes/yahrzeit-theme/Candle_images/candle_end.gif", timeout: 16560000});

//Set the interval with the first element
var x = 0;
var timeout = window.setTimeout(function() {
  changeImage()
}, images[x].timeout);

function changeImage() {
  document.getElementById('candle').src = images[x].src;
  if (x < images.length) {
    x += 1;
  } else {
    x = 0;
  }
  timeout = window.setTimeout(function() {
    changeImage()
  }, images[x].timeout);
}

The timer works okay if the time is in seconds, but I need it to be in hours. Specifically, one hour for the first image and the rest split over the 24 hour period. Could it be that the seconds count is too long? Does it HAVE to be in Milliseconds?

Upvotes: 0

Views: 43

Answers (2)

V&#237;tor Martins
V&#237;tor Martins

Reputation: 1440

setTimeout uses a 32 bit int to store the delay so the maximum value possible is 2147483647.

So that gives you a maximum of 596.52 hours which is more than enough for what you need.

But yes, it has to be in milliseconds because that's the only unit setTimeout() accepts.

Unless you add conversion logic before sending the values to the function.

Upvotes: 1

David Espino
David Espino

Reputation: 2187

Well the function requires miliseconds, but you can have that conversion logic in your function:

function changeImage() {
  document.getElementById('candle').src = images[x].src;
       if (x<images.length) {
         x+=1;
       }else{
         x=0;
  }
  var milisecondTimeout = 1000 * 3600 * images[x].timeout;
  timeout = window.setTimeout(function() {changeImage()}, milisecondTimeout);
  }

And then you could push your images with hours instead of miliseconds:

images.push({src: "http://www.mountsinaiparks.org/digital-yahrzeit/wp-content/themes/yahrzeit-theme/Candle_images/Candle01.gif", timeout: 1});

Hope this helps

Upvotes: 1

Related Questions