Trying to make automated traffic lights - javascript

Hi Im trying to make a set of automated traffic lights but I can't get them to stop running. I have tried using window.clearInterval() but it won't work. Im doing this for my controlled assessment for my GCSE. I really don't know why this won't work so any help would be great. Thanks.
var asset = [
"redyellow.png",
"green.png",
"yellow.png",
"red.png"
];
var counter = 0;
function changeLights() {
if (counter == asset.length) counter = 0;
var image = document.getElementById('redImg');
image.src=asset[counter];
counter = counter + 1;
}
var toggle = 1
function timer() {
if (toggle === 1) {
var on = setInterval(changeLights,5000)
}
else {
window.clearInterval()
}
}
function stopTimer() {
toggle = toggle + 1
}
<!DOCTYPE html>
<html>
<body>
<h1>Traffic Lights</h1>
<img id="redImg" src="red.png" alt="Red traffic light" />
<p>
<button type="button" onclick="timer()">Start Lights</button>
<button type="button" onclick="stopTimer()">Stop Lights</button>
</p>
</body>
</html>

Try making the interval a global variable. Also you need to call self.clearInterval(interval). For example:
var interval;
function timer() {
interval = self.setInterval(changeLights, 5000);
}
function stopTimer() {
self.clearInterval(interval);
}
In your case:
var asset = [
"redyellow.png",
"green.png",
"yellow.png",
"red.png"
];
var counter = 0;
var interval = null;
function changeLights() {
if (counter == asset.length) counter = 0;
var image = document.getElementById('redImg');
image.src = asset[counter];
image.alt = asset[counter]; // debug
counter = counter + 1;
}
function timer() {
if (!interval) {
interval = self.setInterval(changeLights, 1000);
}
}
function stopTimer() {
self.clearInterval(interval);
interval = null;
}
<!DOCTYPE html>
<html>
<body>
<h1>Traffic Lights</h1>
<img id="redImg" src="red.png" alt="Red traffic light" />
<p>
<button type="button" onclick="timer()">Start Lights</button>
<button type="button" onclick="stopTimer()">Stop Lights</button>
</p>
</body>
</html>
Note that I changed it in some ways, most notably removing the code having to do with toggle. This version also allows you to start it again without reloading the page, and prevents you from starting multiple intervals, which would require reloading the page to stop.

Related

JavaScript Traffic light system using setInterval

I have make a traffic light system using javascript and used the setInterval to make it go by itself, however how can i make the timings different? for example i would like the red light and green light to stay on longer then amber and red amber.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript</h1>
<h2>Learning to code</h2>
<p>This is my very first JavaScript task</p>
<img id="traffic" src="red.png">
<button type="button" onclick="dosomething()">something magical will happen if you press me</button>
<script>
var list = ["red.png", "redamber.png", "green.png", "amber.png"];
var index = 0;
var timer = setInterval(dosomething, 3000)
function dosomething(){
index = index + 1;
if (index == list.length) index = 0
var image = document.getElementById('traffic');
image.src=list[index];
}
</script>
</body>
</html>
Here is an example using a weighted-time similar to what I was explaining in my comment. I don't have your images so I replaced them with text.
function changeColors(){
if (index >= list.length) index = 0;
let item = list[index];
if (!item.countdown) item.countdown = item.weight - 1;
else item.countdown = item.countdown - 1;
var image = document.getElementById('traffic');
image.innerHTML=list[index].color+'-'+item.countdown;
if (item.countdown == 0) index = index + 1;
}
var list = [
{color:"red.png", weight:1},
{color:"redamber.png", weight:3},
{color:"green.png", weight:2},
{color:"amber.png", weight:1}
];
var index = 0;
let btnChangeColors = document.getElementById('btnChangeColors');
btnChangeColors.onclick = function() {
var timer = setInterval(changeColors, 1000);
};
<h1>JavaScript</h1>
<h2>Learning to code</h2>
<div id="traffic"/>
<button type="button" id="btnChangeColors">Start Traffic Light</button>

JavaScript Page Rotate with Pause/Play

Please note it can ONLY be JavaScript. Please see below my current HTML.
I need to rotate between pages as the code currently does. BUT, I need to be able to pause/play between the pages.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<iframe id="rotator" src="http://www.example.com" onload="this.width=1000;this.height=750;"></iframe>
<script>
// start when the page is loaded
window.onload = function () {
var urls = [
"http://www.example.com",
"http://www.example2.com",
// ....
"http://www.example3.com"
];
var index = 1;
var el = document.getElementById("rotator");
setTimeout(function rotate() {
if (index === urls.length) {
index = 0;
}
el.src = urls[index];
index = index + 1;
// continue rotating iframes
setTimeout(rotate, 15000);
}, 15000); // 5000ms = 5s
};
</script>
</body>
</html>
use setInterval and clearInterval method as like this below
var run;
var el =document.getElementById('rotator');
var urls = [
"http://www.example.com",
"http://www.example2.com",
"http://www.example3.com"
];
(function()
{
run = setInterval(rotate , 1000)
console.log('start')
})()
var index=0;
function rotate(){
if (index === urls.length) {
index = 0;
}
el.src = urls[index];
index ++;
}
function pause(){
clearInterval(run);
console.log('pause')
}
function play(){
run = setInterval(rotate , 1000);
console.log('play');
}
<iframe id="rotator" src="http://www.example.com" ></iframe>
<button onclick="pause()">
pause
</button>
<button onclick="play()">
play
</button>

Traffic light Sequence Javascript

Here is my code for a traffic light's sequences. I was wondering how I could add a timer in to change the traffic light colour every 3 seconds, for example, when the button is clicked. Thanks!
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Task 3</h1>
<p>This is my Traffic Light script</p>
<img id="light" src="./assets/red.jpg">
<button type="button" onclick="changeLights()">Change Lights</button>
<script>
var list = ["./assets/red.jpg","./assets/redamber.jpg", "./assets/green.jpg","./assets/amber.jpg" ];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length)
index = 0;
var image = document.getElementById('light');
image.src = list[index];
}
</script>
</body>
</html>
Use the setInterval function.
The first parameter is the function you want to call and the second parameter is how often it should be called, in milliseconds.
var timer = setInterval(changeLights,3000);
var list = ["./assets/red.jpg","./assets/redamber.jpg", "./assets/green.jpg","./assets/amber.jpg" ];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length)
index = 0;
var image = document.getElementById('light');
image.src=list[index]; }
var timer = setInterval(changeLights,3000);
<h1>JavaScript Task 3</h1>
<p>This is my Traffic Light script</p>
<img id="light" src="./assets/red.jpg"> <button type="button"
onclick="changeLights()">Change Lights</button>
You can set a static timer with setTimeout(function, time);
In your case, if you want a repeating timer every 3 seconds constantly, you can have setTimeout run every time the changeLights() function ends
See w3schools article on timing
var timer;
function changeLights() {
index = index + 1;
if (index == list.length)
index = 0;
var image = document.getElementById('light');
image.src=list[index];
timer = setTimeout("changeLights", 3000);
}
With that change, once you start the lights, the function will repeat every 3 seconds.
The timer variable also alows you to stop the timer (perhaps in your case with another button) with:
clearTimeout(timer);
Hope this helps

Onclick reset setInterval

<!DOCTYPE html>
<html>
<head>
<script>
function timer(x) {
if (x == 1) {
//reset timer
}
var i = 0;
var timer = setInterval(function() {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 500);
}
</script>
</head>
<body>
<p id="demo">hello</p>
<button type="button" onclick="timer(0)">change</button>
<button type="button" onclick="timer(1)">reset</button>
</body>
</html>
I want to reset timer onclick . e.g. if setIntervaltime is set to 5 sec and 3 seconds are elapsed ,after that if some on click on reset button it should start gain from 5 seconds.How to do this.
Keep the return value of setTimeout somewhere that you can get it again (currently you are storing it in a local variable, so it goes away when the function ends)
Call clearTimeout(timer);
Call setTimeout with whatever arguments you want again.
As already Quentin mentioned, use clearInterval to solve your problem.
Wrap it within an if.else.. statement like
if(x == 1) {
clearTimeout(timeout);
}
else {
timeout = setInterval..... // otherwise even after resetting
// it will continue to increment the value
}
Complete Code:
var timeout; // has to be a global variable
function timer(x) {
var i = 0;
if (x == 1) {
clearTimeout(timeout);
document.getElementById("demo").innerHTML = i;
} else {
timeout = setInterval(function () {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 1000);
}
}
JSFiddle

timer using javascript

I want implement timer using java script.I want to decrement timer with variation of interval.
Example.Suppose my timer starts at 500 .
I want decrement timer depending on the level such as
1. 1st level timer should decrement by 1 also decrement speed should be slow.
2.2nd level timer should decrement by 2 and decrement speed should be medium
3.3rd level timer should decrement by 3 and decrement speed should be fast
I can create timer using following code:
<script type="text/javascript">
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time)
{
TotalSeconds=Time;
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer();
setTimeout("Tick()", 1000);
}
function Tick() {
TotalSeconds -= 10;
if (TotalSeconds>=1)
{
UpdateTimer();
setTimeout("Tick()", 1000);
}
else
{
alert(" Time out ");
TotalSeconds=1;
Timer.innerHTML = 1;
}
}
But i call this CreateTimer() function many times so its speed is not controlling because i call it many times.
Couple of points:
You've used all global variables, it's better to keep them private so other functions don't mess with them
Function names starting with a captial letter are, by convention, reserved for constructors
The function assigned to setTimeout doesn't have any public variables or functions to modify the speed while it's running so you can only use global variables to control the speed. That's OK if you don't care about others messing with them, but better to keep them private
The code for UpdateTimer hasn't been included
Instead of passing a string to setTimeout, pass a function reference: setTimeout(Tick, 1000);
Anyhow, if you want a simple timer that you can change the speed of:
<script>
var timer = (function() {
var basePeriod = 1000;
var currentSpeed = 1;
var timerElement;
var timeoutRef;
var count = 0;
return {
start : function(speed, id) {
if (speed >= 0) {
currentSpeed = speed;
}
if (id) {
timerElement = document.getElementById(id);
}
timer.run();
},
run: function() {
if (timeoutRef) clearInterval(timeoutRef);
if (timerElement) {
timerElement.innerHTML = count;
}
if (currentSpeed) {
timeoutRef = setTimeout(timer.run, basePeriod/currentSpeed);
}
++count;
},
setSpeed: function(speed) {
currentSpeed = +speed;
timer.run();
}
}
}());
window.onload = function(){timer.start(10, 'timer');};
</script>
<div id="timer"></div>
<input id="i0">
<button onclick="
timer.setSpeed(document.getElementById('i0').value);
">Set new speed</button>
It keeps all its variables in closures so only the function can modify them. You can pause it by setting a speed of zero.
Hope, this could be helpful:
<html>
<head>
<script type="text/javascript">
function showAlert()
{
var t=setTimeout("alertMsg()",5000);
}
function alertMsg()
{
alert("Time up!!!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Start" onClick="timeMsg()" />
</form>
</body>
</html>
Check this demo on jsFiddle.net.
HTML
<div id="divTimer">100</div>
<div id="divDec">1</div>
<div id="divSpeed">100</div>
<input id="start" value=" Start " onclick="javaScript:start();" type="button" />
<input id="stop" value=" Stop " onclick="javaScript:stop();" type="button" /><br/>
<input id="inc" value=" Increase " onclick="javaScript:increase();" type="button" />
<input id="dec" value=" Decrease " type="button" onclick="javaScript:decrease();"/>​
JavaScript
var handler;
function start() {
handler = setInterval("decrementValue()", parseInt(document.getElementById('divSpeed').innerHTML, 10));
}
function stop() {
clearInterval(handler);
}
function decrementValue() {
document.getElementById('divTimer').innerHTML = parseInt(document.getElementById('divTimer').innerHTML, 10) - parseInt(document.getElementById('divDec').innerHTML, 10);
}
function increase() {
document.getElementById('divDec').innerHTML = parseInt(document.getElementById('divDec').innerHTML, 10) + 1;
document.getElementById('divSpeed').innerHTML = parseInt(document.getElementById('divSpeed').innerHTML, 10) + 200;
stop();
decrementValue();
start();
}
function decrease() {
document.getElementById('divDec').innerHTML = parseInt(document.getElementById('divDec').innerHTML, 10) - 1;
document.getElementById('divSpeed').innerHTML = parseInt(document.getElementById('divSpeed').innerHTML, 10) - 200;
stop();
decrementValue();
start();
}​
Hope this is what you are looking for.

Categories