0

My JS page

const catImage=document.querySelector('img')

let catImageLeft=catImage.style.left='0px'

function catwalk() {

    let position= 0
    setInterval(frame,50)

    function frame() {

        position+=10
        catImage.style.left=position+'px'

        if (position==1080) {
            return catwalk()
        } 
    if (position==540) {
            setTimeout(catImage.src='https://media1.tenor.com/images/2de63e950fb254920054f9bd081e8157/tenor.gif',1000)
        }
    }

}

As you can see, it keeps on moving after replacing the image. And also if i would like the image to start over again, it stutters.

any suggestions.

3
  • I do not really understand what you want, you want the cat walking gif to be visible from left=0 to left=540 and the cat dancing gif from left=540 to left=1080 and then start again from 0 infinitely ? Commented Dec 20, 2019 at 10:48
  • What I want is to make the walking gif from 0 till 520, then the dancing GIF at 540 pause while the gif runs for a couple of seconds. Then continue from 560 with the walking gif till 1080 then start over again. Commented Dec 20, 2019 at 10:56
  • 1
    jsfiddle.net/bftj7hpd Commented Dec 20, 2019 at 11:03

1 Answer 1

2

Try this!

const catImage = document.querySelector('img');
const catWalkimg = 'https://i.imgur.com/Akh489w.gif';
const catDancImg = 'https://media2.giphy.com/media/3mXcJgVhPxWZa/giphy.gif';

catwalk();

function catwalk() {
  let position = 0;
  setInterval(function() {

    position = position > 700 ? 0 : position;

    if (position == 350) {
      if (catImage.src != catDancImg) {
        catImage.src = catDancImg;
        setTimeout(() => {
          catImage.src = catWalkimg;
          position += 10;
        }, 2000);

      }

    } else {
      catImage.style.left = position + 'px';
      position += 10;
    }
  }, 50);
}
img {width: 160px}
<img style="position:absolute;" src="https://i.imgur.com/Akh489w.gif" />

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.