0

I need to display four images at different time intervals either using html or javascript.

First image 2 seconds Second image 2.5 seconds Third image 5 seconds Fourth image 2.5 seconds

I have seen some examples on having them change on a set interval, but not sure how to setup with different intervals.

Any assistance would be super helpful!

Thanks so much!

mlanyon
  • 1
  • 1
  • Show your markup and your script that you have tried so we may help you fix it – Mark Schultheiss Jun 24 '21 at 17:39
  • There are a number of ways to do this, but I'd suggest using CSS animations and set a delay. https://stackoverflow.com/questions/29846224/css-animation-with-delay-and-opacity – ezekielDFM Jun 24 '21 at 17:52

2 Answers2

0

You can use Promises:

const img = document.querySelector('img');
const cycleImages = ["https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1",
  "https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=96&d=identicon&r=PG&f=1",
  "https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=144&d=identicon&r=PG&f=1",
  "https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=192d=identicon&r=PG&f=1"
]

async function cycle() {
  img.src = cycleImages[0];
  await new Promise(r => setTimeout(r, 2000));
  img.src = cycleImages[1];
  await new Promise(r => setTimeout(r, 2500));
  img.src = cycleImages[2];
  await new Promise(r => setTimeout(r, 5000));
  img.src = cycleImages[3];
  await new Promise(r => setTimeout(r, 2500));
  cycle();
}
cycle();
<img>
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

Here's one method - use a function to setTimeout and call itself until completed. When you run the snippet below, observe the console.log to see when the new images are inserted. Also, this has 5 images - the first being the default image that shows until the first image loads 2 seconds later.

let n = 0,
  timeouts = [0, 2, 2.5, 5, 2.5],
  imgs = ['default-beginning-image.jpg', 'img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg'
  ];
const doImages = (num) => {
  setTimeout(() => {
    console.log('show', imgs[num])
    document.querySelector('[data-changer]').setAttribute('src', imgs[num]);
    if (num++ < imgs.length) doImages(num);
  }, timeouts[num] * 1000)
}

doImages(n);
<img data-changer src='' />
Kinglish
  • 23,358
  • 3
  • 22
  • 43