S SAM
S SAM

Reputation: 211

Javascript two interval image change

I have an image that I want to stay on screen for 5 seconds and then change to another image for .5 of a second and then change back to the original.

I've set the interval to change every 5 seconds but I can't seem to work out how to make it change for the according times.

Any help or direction would be greatly appeciated!

window.setInterval(function() {

  var img = document.getElementById("glitch");
  img.src = "2-01.svg";

}, 5000);

Upvotes: 1

Views: 182

Answers (3)

Jeremy-F
Jeremy-F

Reputation: 113

I was doing some test watching the thread.

If that can help you (this is not a clean code) :

img_to_change = document.querySelector("#glitch");

imgs = {"a":10, "b":2, "c":3}
keys = Object.keys(imgs)
run = function(i){
  img_src = keys[i];
  img_next_time = imgs[keys[i]];
  img_to_change.src = img_src;
  i = (i+1) == keys.length ? -1 : i;
  setTimeout(() => {
    img_to_change.src = img_src;
    run(i+1);
  }, img_next_time*1000)
}
run(0);

http://jsfiddle.net/pn3dyb5m/32/

Upvotes: 0

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21881

Try this:

const images = ["1.svg", "2.svg"]
var element = document.getElementById("glitch");

function showFirst() {
  setTimeout(() => {
    element.src = images[0];
    showSecond()
  }, 5000)
}

function showSecond() {
  setTimeout(() => {
    element.src = images[1];
    showFirst()
  }, 500)
}

showFirst()

Upvotes: 3

WarPro
WarPro

Reputation: 350

You are always changing the image src to same "2-01.svg" every time. Please use some flag/condition to alternate the image src.

Here is what you can try ::

window.setInterval(function() {

  var img = document.getElementById("glitch");
  if(img.src == "2-01.svg") {
     img.src = "2-00.svg"
  }
  else {
    img.src = "2-01.svg";
  }
}, 5000);

Upvotes: 0

Related Questions