0

I am trying to have an image change every tenth of a second. I have written a script based off other responses on here and it is still not working. Here is the script:

var images = Array();
var index = 0;
images = ["rock.png", "paper.png", "scissors.png"];
var opponent = document.getElementById("opps");

setInterval(myMethod, 100);

function myMethod( ){
    opponent.src = images[index];

    if (index <= 1){
        index++;
    }
    else{
        index = 0;
    }
}

Here is the tag:

<img src = "" id ="opps"/>
TDonnally
  • 67
  • 10
  • Does this answer your question? [Javascript set img src](https://stackoverflow.com/questions/1232793/javascript-set-img-src) – cereme Dec 24 '19 at 01:04
  • It does not. I am getting this error: Error: Uncaught TypeError: Cannot set property 'src' of null at myMethod – TDonnally Dec 24 '19 at 01:09

3 Answers3

1

You can do index % images.length to infinitely loop over the array - when you go over the index, it'll just wrap back around

Also, you should use let a = [] to create an empty Array. You don't have to, but it's good practice - Read more

Finally, 100 miliseconds is probably a little too often to change an image src, about 1 - 5 seconds should be plenty in most cases

var images = ["rock.png", "paper.png", "scissors.png"];
var index = 0;
var opponent = document.getElementById("opps");

setInterval(myMethod, 100);

function myMethod( ){
    opponent.src = images[index % images.length];
    index += 1;
    
    console.log(opponent.src);
}
<img src = "" id ="opps"/>
Shiny
  • 4,945
  • 3
  • 17
  • 33
1

I figured it out. To anyone else with this error it is due to having your script run before your html. Run script after your img.

TDonnally
  • 67
  • 10
0

Your code worked, the strings in the images array were relative so maybe you didn't have them in your project. I've simplified a few things, first I initialize and declare the images array in the same expression, and second, I turned your if statement in myMethod() into a ternary expression:

let index = 0
const images = [
  "http://placekitten.com/200/200", 
  "http://placekitten.com/210/210", 
  "http://placekitten.com/220/220"
]

const opponent = document.getElementById("opps");

setInterval(myMethod, 1000)

function myMethod(){
    opponent.src = images[index];

    index = index <= 1 ? index + 1 : 0
}
<img src="" id="opps"/>
symlink
  • 11,984
  • 7
  • 29
  • 50