Reputation: 49
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
Reputation: 3908
Here's your code in a working example.
Here are a few pointers as to what I improved:
pos
out of the function as each time it is called, it will be reset to 1.var
, let
or const
the first time you initiate a variable.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
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
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