James Furious
James Furious

Reputation: 49

Images with Interval for animation

I'm going to use if else for creating an animation with a certain interval for each image but it's not working, it made me confused please anyone tell me what's wrong with my code. Here is my code:

var j = setInterval(james, 5);

function james() {
  var pos = 1;
  if (pos >= 6) {
    clearInterval(j);
    document.getElementsByTagName('img')[0].setAttribute('src', 'https://www.ptcrush.com/' + pos + '.gif');
  } else {
    var pos += 1;
    document.getElementsByTagName('img')[0].setAttribute('src', 'https://www.ptcrush.com/' + pos + '.gif');
  }
}
<img />
<button onclick="james()">Halo</button>

Thanks in advance

Upvotes: 2

Views: 205

Answers (3)

Roy Scheffers
Roy Scheffers

Reputation: 3908

Here's your code in a working example.

Here are a few pointers as to what I improved:

  1. Move pos out of the function as each time it is called, it will be reset to 1.
  2. No need to clear the interval unless you want to stop the animation after one round.
  3. remove var in the else statement. As you already define it above, there's no need to do it again. Only use var, let or const the first time you initiate a variable.
  4. I've increased the interval to 3 seconds setInterval(james, 3000) else the animation would be running too fast. Tweak as you see fit.

var j = setInterval(james, 3000);

var pos = 1;

function james() {
  if (pos >= 6) {
    pos = 1;
    document.getElementsByTagName('img')[0].setAttribute('src', 'https://www.ptcrush.com/' + pos + '.gif');
  } else {
    pos += 1;
    document.getElementsByTagName('img')[0].setAttribute('src', 'https://www.ptcrush.com/' + pos + '.gif');
  }
}
<img />
<p><button onclick="james()">Hallo</button></p>

Upvotes: 1

darklightcode
darklightcode

Reputation: 2772

You need to put outside the function the variable pos and you need to increase the timeout because by the time your new image will load, the timer will load a new image

var pos = 1;
var j = setInterval(james, 4000);

function james() {
  if (pos >= 6) {
    clearInterval(j);
    document
      .getElementsByTagName('img')[0]
      .setAttribute('src', 'https://www.ptcrush.com/' + pos + '.gif');
  } else {
    pos += 1;
    document
      .getElementsByTagName('img')[0]
      .setAttribute('src', 'https://www.ptcrush.com/' + pos + '.gif');
  }
  console.log('pos', pos);
}
<img width="200" height="200" src="" />

Upvotes: 0

Shaharyar
Shaharyar

Reputation: 12439

remove var from line:

var pos += 1;

Also move the variable initialization to outside the function:

var pos = 1;
function james() {
    ...

Upvotes: 1

Related Questions