pythonnoob
pythonnoob

Reputation: 23

How do I solve this issue of the pictures not changing?

Hey so i developed this code to allow me to change the images based on a timer. As the countdown hits certain milestones the picture changes. But unfortunately I cannot get this to work as intended.

<!DOCTYPE html>
<html>
<body>
<h1> Change the lights automatically</h1>

<img id="myimg" src="1.png" width ="100" height="300">

<script>

var list = [
    "1.jpg",
    "2.jpg",
    "3.jpg",
    "4.jpg"
];

var count = 0;
var time=20;

var timing=setInterval(timer, 1000); //1000 will  run it every 1 second

function timer()
(
    var newImage = document.getElementById('myimg');
    time = time-1

    if (time <= 1) time = 20;
    if (time >15 && time < 21) count = 0;
    if (time >10 && time <16) count = 1;
    if (time >6 && time <15) count = 2;
    if (time >1 && time <5) count = 3;
    if (time = 0) count = 0;

    var newImage = document.getElementById('myimg');
    newImage.src = list[count];
}

</script>
</body>
</html>

What I have do is , the code should have a timer that runs every one second, when the timer is between a certain amount the value of count should change accordingly. Afterwards as i have set the new image to be changed each time the value of count changes , the image displayed should change however this is not the case as it doesn't change. Any experts out there can identify what is wrong with it so i can fix it? Thanks in advance!

Upvotes: 2

Views: 111

Answers (3)

Geeky
Geeky

Reputation: 7496

This is because your time is always 19 or time-1 on the timer function you might consider taking a look this javascript setInterval() and Variable Scope

Hope this helps

check the following code snippet

var list = [
    "1.jpg",
    "2.jpg",
    "3.jpg",
    "4.jpg"
];

var count = 0;
var time=20;

var timing=setInterval(timer, 1000); 
function timer()
{
var newImage = document.getElementById('myimg');
  
  time=time-1;
    if (time <= 1) time = 20;
    else if (time >15 && time < 21) count = 0;
    else if (time >10 && time <16) count = 1;
    else if (time >6 && time <15) count = 2;
    else if (time >1 && time <7){ count = 3;}
    else if (time == 0) count = 0;
  else 
  {
  clearInterval(timing);
  return;
  }
    var newImage = document.getElementById('myimg');
  console.log(newImage.src);
    newImage.src = list[count];
  }
<img id="myimg" src="1.png" width ="100" height="300">

Upvotes: 0

Dan Nagle
Dan Nagle

Reputation: 5425

The final if condition assigns time to 0.

if (time = 0) count = 0;

time will always be 0 so

newImage.src = list[count];

always displays the same image. Remove the final if condition and amend the first one.

if ((time >15 && time < 21) || (time == 0)) count = 0;

Upvotes: 2

jay
jay

Reputation: 1770

You missed the curly brace here...

function timer() (

... it should be

function timer() {

Upvotes: 0

Related Questions