I am new to JavaScript and i am tying to automate this traffic light sequence. I have used if and if else statements to preform the task but I am unable to automate it so it
I would clean things up a bit... you can move all the drawing to one place. Then use a start and stop function. Actually, you can easily combine the start and stop but I will leave that to you. Here you go:
function light(c) {
this.current = 0;
this.colors = ["green", "yellow", "red"];
this.ctx = c.getContext("2d");
}
light.prototype.draw = function() {
this.ctx.beginPath();
this.ctx.arc(95, 50, 40, 0, 12 * Math.PI);
this.ctx.fillStyle = this.colors[this.current];
this.ctx.fill();
}
light.prototype.start = function() {
if(this.interval)
return;
this.draw();
this.interval = setInterval(function() {
this.current = (this.current + 1) % this.colors.length;
console.log("drawing: ", this.colors[this.current]);
this.draw();
}.bind(this), 3000);
}
light.prototype.stop = function() {
if (!this.interval)
return;
clearInterval(this.interval);
delete this.interval;
}
var myLight = new light(document.getElementById("myCanvas"));