Below is my code for some of my coursework(I will admit). As you can see in the comments i have done the 'setinterval' with a button. But what I want is the 'setInterval' to be able to run automatically. What i mean by this is I do not want the user to have to click the button. Is there a way to do this and if so could you point me in the right direction.
<!DOCTYPE html>
<html>
<head>
<title>Task 3 Manual traffic lights</title>
</head>
<body>
<h1>JavaScript Task 3</h1>
<p >This is my Traffic Light script</p>
<img id="change-light" src="red_traffic_light.png" width="150" height="300" align=middle>
<!-- <button onclick="setInterval(changelights, 1000)" >Start the timer</button> -->
<script>
var list = ["red_traffic_light.png", "red-amber-traffic-light.png","green_traffic_light.png", "amber-traffic-light.png"
];
var index = 0
function changelights() {
index = index + 1
if (index == list.length) index = 0;
var image = document.getElementById('change-light');
image.src=list[index];
}
</script>
</body>
</html>
Just put setInterval(changelights, 1000)
inside your script tag.
when browser run that line of code. it will start the timer.
<script>
setInterval(changelights, 1000);
</script>
Call it when your document is ready:
With jQuery :
$( document ).ready(function() {
setInterval(changelights, 1000);
});
Pure javascript:
(function() {
setInterval(changelights, 1000);
})();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.