Zhyohzhy Zhyohzhy - 1 year ago 74
Javascript Question

Changing images using delays

I’m trying to figure out how to make an animation using the order of three images.

The default image is “image1.png” that always shows when the page loads.

  1. After every 5 seconds, the variable “back.src” must abruptly change
    to image2.png, so without fading. The default is image1.png

  2. And then after 0.5 seconds, the variable again changes but then to

  3. 0.5 seconds later it changes back to image2.png

  4. and 0.5 later again back to image1.png.

This is to be repeated in a loop because I want to repeat the process again after 5 seconds.

My problem is, I don't know if structuring this code is the best way to go about it. How would my code need to look based on the requirement explained above?

Here's my code of what I've got so far:

var back = new Image();
back.src = "image1.png";
function wait(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {

function image1() {
back.src = "image2.png";

function image2() {
back.src = "image3.png";

function image3() {
back.src = "image2.png";

function animate(){
ctx.clearRect(0, 0, cW, cH);
var animateInterval = setInterval(animate, 30);

Answer Source

You can achieve it using setIterval()

Read about JS Timers Here

Here is what you need : https://jsfiddle.net/nfe81zou/3/

var image1 = "https://pixabay.com/static/uploads/photo/2016/06/17/13/02/duck-1463317_960_720.jpg";
var image2 = "https://pixabay.com/static/uploads/photo/2013/09/22/16/56/duck-185014_960_720.jpg";
var image3 = "https://pixabay.com/static/uploads/photo/2013/11/02/03/23/ducks-204332_960_720.jpg";

$(function() {
  $("#image").prop("src", image1);
  setInterval(function() {
$("#image").prop("src", image2);
setTimeout(function() {
  $("#image").prop("src", image1);
  setTimeout(function() {
    $("#image").prop("src", image3);
  }, 500);
  setTimeout(function() {
    $("#image").prop("src", image2);
  }, 1000);
}, 1500);
  }, 5000);
#image {
  border: 2px solid red;
  width: 400px;
  height: 200px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="" id="image"/>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download