What are the steps to creating a traffic light that operates automatically?

var RED = "#FF0000";
        var YELLOW = "#FFFF00";
        var GREEN = "#00FF00";
        var DARK_RED = "#380000";
        var DARK_YELLOW = "#383800";
        var DARK_GREEN = "#003800";
        var X_ALL = 150;
        var Y_RED = 100;
        var Y_YELLOW = Y_RED + 150;
        var Y_GREEN = Y_YELLOW + 150;
        var trafficLightsStateMachine;
        function TrafficLightsStateMachine() {
          this.state = 0;
          this.stateMachine = new Array();
          this.stateMachine[0] = function () { drawCircles(DARK_RED, YELLOW, DARK_GREEN); };
          this.stateMachine[1] = function () { drawCircles(RED, DARK_YELLOW, DARK_GREEN); };
          this.stateMachine[2] = function () { drawCircles(RED, YELLOW, DARK_GREEN); };
          this.stateMachine[3] = function () { drawCircles(DARK_RED, DARK_YELLOW, GREEN); };
          this.process = function() {
            this.stateMachine[this.state]();
            this.state = (this.state + 1) % this.stateMachine.length;
          };
          this.drawCircle = function(canvas, color, x, y) {
            var context = canvas.getContext('2d');
            context.strokeStyle = "#000000";
            context.fillStyle = color;
            context.beginPath();
            context.arc(x, y, 50, 0, Math.PI * 2, true);
            context.closePath();
            context.stroke();
            context.fill();
          };
        }
        
        function drawCircles(first, second, third) {
          var id = 'canvas';
          var canvas = document.getElementById(id);
          if (canvas.getContext) {
            trafficLightsStateMachine.drawCircle(canvas, first, X_ALL, Y_RED);
            trafficLightsStateMachine.drawCircle(canvas, second, X_ALL, Y_YELLOW);
            trafficLightsStateMachine.drawCircle(canvas, third, X_ALL, Y_GREEN);
          }
        }
        
        function init() {
          trafficLightsStateMachine = new TrafficLightsStateMachine();
          drawCircles(DARK_RED, DARK_YELLOW, GREEN);
        }
#page
        {
          width: 300px;
          height: 500px;
          margin: auto;
        }
        #canvas:hover
        {
          cursor: crosshair;
          background-color: #191919;
        }
        #canvas
        {
          background-color: #252525;
        }
        body
        {
          background: #222222;
          color: white;
        }
<body onload="init()">
        <div id="page" onclick="trafficLightsStateMachine.process()" title="Please, press button.">
        <canvas id="canvas" height="500px" width="300px">
        </canvas>
        </div>
        </body>

I am seeking the modification of this code to automate the change of the traffic light sequence. I understand that I must insert

setinterval(trafficLightsStateMachine.process,1000)
but unsure regarding its placement. Your guidance is appreciated.

Answer №1

  1. Get rid of the body onload init
  2. Delete the onclick from the div element
  3. Include an event handler for onload like this:

window.onload=function() { 
  init(); 
  setInterval(
    trafficLightsStateMachine.process.bind(trafficLightsStateMachine),
  1000); // necessary syntax to use "this" in the stateMachine
}

Output:

var RED = "#FF0000";
var YELLOW = "#FFFF00";
var GREEN = "#00FF00";
var DARK_RED = "#380000";
var DARK_YELLOW = "#383800";
var DARK_GREEN = "#003800";
var X_ALL = 150;
var Y_RED = 100;
var Y_YELLOW = Y_RED + 150;
var Y_GREEN = Y_YELLOW + 150;
var trafficLightsStateMachine;
function TrafficLightsStateMachine() {
  this.state = 0;
  this.stateMachine = new Array();
  this.stateMachine[0] = function () { drawCircles(DARK_RED, YELLOW, DARK_GREEN); };
  this.stateMachine[1] = function () { drawCircles(RED, DARK_YELLOW, DARK_GREEN); };
  this.stateMachine[2] = function () { drawCircles(RED, YELLOW, DARK_GREEN); };
  this.stateMachine[3] = function () { drawCircles(DARK_RED, DARK_YELLOW, GREEN); };
  this.process = function() {
    this.stateMachine[this.state]();
    this.state = (this.state + 1) % this.stateMachine.length;
  };
  this.drawCircle = function(canvas, color, x, y) {
    var context = canvas.getContext('2d');
    context.strokeStyle = "#000000";
    context.fillStyle = color;
    context.beginPath();
    context.arc(x, y, 50, 0, Math.PI * 2, true);
    context.closePath();
    context.stroke();
    context.fill();
  };
}

function drawCircles(first, second, third) {
  var id = 'canvas';
  var canvas = document.getElementById(id);
  if (canvas.getContext) {
    trafficLightsStateMachine.drawCircle(canvas, first, X_ALL, Y_RED);
    trafficLightsStateMachine.drawCircle(canvas, second, X_ALL, Y_YELLOW);
    trafficLightsStateMachine.drawCircle(canvas, third, X_ALL, Y_GREEN);
  }
}

function init() {
  trafficLightsStateMachine = new TrafficLightsStateMachine();
  drawCircles(DARK_RED, DARK_YELLOW, GREEN);
}
window.onload=function() {
  init();
  setInterval(trafficLightsStateMachine.process.bind(trafficLightsStateMachine),1000);
}
#page
{
  width: 300px;
  height: 500px;
  margin: auto;
}
#canvas:hover
{
  cursor: crosshair;
  background-color: #191919;
}
#canvas
{
  background-color: #252525;
}
body
{
  background: #222222;
  color: white;
}
    <canvas id="canvas" height="500px" width="300px"></canvas>

Answer №2

Make sure to include

setInterval(trafficLightsStateMachine.process,1000)
at the end of the init() function.

Answer №3

trafficLightsStateMachine.process()

const RED = "#FF0000";
const YELLOW = "#FFFF00";
const GREEN = "#00FF00";
const DARK_RED = "#380000";
const DARK_YELLOW = "#383800";
const DARK_GREEN = "#003800";
const X_ALL = 150;
const Y_RED = 100;
const Y_YELLOW = Y_RED + 150;
const Y_GREEN = Y_YELLOW + 150;
let trafficLightsStateMachine;
function TrafficLightsStateMachine() {
  this.state = 0;
  this.stateMachine = new Array();
  this.stateMachine[0] = function () { drawCircles(DARK_RED, YELLOW, DARK_GREEN); };
  this.stateMachine[1] = function () { drawCircles(RED, DARK_YELLOW, DARK_GREEN); };
  this.stateMachine[2] = function () { drawCircles(DARK_RED, YELLOW, DARK_GREEN); };
  this.stateMachine[3] = function () { drawCircles(DARK_RED, DARK_YELLOW, GREEN); };
  this.process = function() {
    this.stateMachine[this.state]();
    this.state = (this.state + 1) % this.stateMachine.length;
  };
  this.drawCircle = function(canvas, color, x, y) {
    const context = canvas.getContext('2d');
    context.strokeStyle = "#000000";
    context.fillStyle = color;
    context.beginPath();
    context.arc(x, y, 50, 0, Math.PI * 2, true);
    context.closePath();
    context.stroke();
    context.fill();
  };
}

function drawCircles(first, second, third) {
  const id = 'canvas';
  const canvas = document.getElementById(id);
  if (canvas.getContext) {
    trafficLightsStateMachine.drawCircle(canvas, first, X_ALL, Y_RED);
    trafficLightsStateMachine.drawCircle(canvas, second, X_ALL, Y_YELLOW);
    trafficLightsStateMachine.drawCircle(canvas, third, X_ALL, Y_GREEN);
  }
}

function init() {
  trafficLightsStateMachine = new TrafficLightsStateMachine();
  drawCircles(DARK_RED, DARK_YELLOW, GREEN);
}
function start()
{
  setInterval(function(){ trafficLightsStateMachine.process(); }, 1000);

}
#page
{
  width: 300px;
  height: 500px;
  margin: auto;
}
#canvas:hover
{
  cursor: crosshair;
  background-color: #191919;
}
#canvas
{
  background-color: #252525;
}
body
{
  background: #222222;
  color: white;
}
<body onload="init()">
  <div id="page" onclick="start()" title="Please, press button.">
    <canvas id="canvas" height="500px" width="300px">
    </canvas>
  </div>
  
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to reposition an element to the end of its flexbox container?

I have a flexbox-container that contains multiple details-elements with flex-wrap behavior. My goal is to have a details-element move below the other elements within the container when it is opened. For example, I want it to go from this initial layout: ...

Ul list centered alignment appears misaligned to the left in Safari browser exclusively

I'm experiencing an issue with my menu alignment. It appears perfectly centered in FF, Chrome, and IE, but shifts to the left in the Safari browser. I'm not sure if there is a specific CSS property I need to use to correct this alignment. <d ...

Choose dropdown menus that are pre-filled by JSON may require a manual refresh to show the content

Occasionally, I encounter an issue with a JSON file used to populate select boxes, where the items in the drop down fail to display until the page is refreshed. Despite no errors in the console or log, the loading is seamless on most occasions, leaving me ...

Steps to cancel an AJAX call in C# .NET:

In the ajax.cs class, I am calling methods from the javascript side. To register this on the default.aspx page load, I did the following: Ajax.Utility.RegisterTypeForAjax(typeof(ajax)); Occasionally, some methods take a long time to execute. In such case ...

Using vue-select: In VueJs, how to pass an option slot from a grandparent component

Utilizing a custom dropdown component called 'vue-select', there is an option to customize the options view using slots as detailed in this documentation -> https://vue-select.org/guide/slots.html I am aiming to achieve a similar customizatio ...

Error with react/display-name in ESLint when using dynamic imports in Next.js

I encountered an error message from ESLint that says: Component definition is missing display name This error occurred in the following code snippet: const Disqus = dynamic(() => import('@/components/blog/disqus'), { ssr: false, loading: ...

Adding a combination of HTML and Javascript to an element can result in unexpected behavior

http://jsfiddle.net/PeKdr/ Encountering an issue when having a JavaScript variable that contains both HTML and JavaScript, resulting in unexpected behavior in the output window. Neither of the buttons - one triggering the function appendTheString() or the ...

Having a parameter that contains the characters '&' and '&' can potentially disrupt an AJAX call

Even though there is a similar question here: Parameter with '&' breaking $.ajax request, the solutions provided do not apply to my specific issue. This is because both the question and answers involve jQuery, which I am not familiar with. I ...

What are the best plugins and projects to maximize IntelliJ IDEA's potential for JavaScript development?

I am currently in the process of developing a web application utilizing the MEAN stack: MongoDB, Express, Angular, and Node.js. The foundation of my project is built upon Daftmonk's angular-fullstack Yeoman generator. Despite my primary experience be ...

Retrieving the value of a child in JSON

I have encountered this JSON structure and I am interested in extracting the value of "resource_uri" which is "/api/v1/client/2/". My implementation revolves around Backbone/javascript. Unfortunately, using json['resource_uri'] does not produce ...

Get an Object Array and assign it to a state Array variable after filtering

Here is a JSON Input that I will be filtering by orderId and then setting to a state variable. [{"orderId":3,"userId":3,"firstName":"Amal","lastName":"kankanige","contactNo":"011-3456787","status":"pending","deliveryAddress":"No:24/c,Anders Road,Wijerama, ...

Ways to delete a header from the req object in Express

Can anyone help me understand how to remove a header from the req object in Express? I've heard that using res.disable("Header Name") can do this for the res object, but it doesn't seem to work for req.headers. ...

Problem with CSS hovering on images when hovering on links?

While attempting to add 2 hover images to my website, I encountered an issue where a black border appeared in the middle of the images. This was caused by the hover effects on the links. Below is the code snippet: a:hover,a:active { color:Black; o ...

The `.append()` function includes HTML content as plain text

I am using JavaScript to dynamically add HTML elements to my webpages. I have created a loop that iterates through all the projects, each containing multiple pictures. The first step involves generating the project title and adding it within a div element ...

Tips for adding a DIV element at the top of a webpage while smoothly sliding down other elements with absolute top:0 CSS styles

I am dealing with a website that has a complex structure of elements and CSS styles, with many elements having `position:absolute` and `top:0` styles applied. There are multiple nested divs due to inheriting the website from a previous owner. I am wonder ...

What could be the reason behind an Ajax Auto-Complete feature suddenly malfunctioning when moving to a new page within the same website?

Working on a website featuring an auto-complete search box powered by Ajax, Javascript, and PHP. As the user types into the search box, an ajax request triggers a php file to query a database and return possible results. Everything works smoothly until the ...

Transform a string into a boolean value for a checkbox

When using v-model to show checked or unchecked checkboxes, the following code is being utilized: <template v-for="(item, index) in myFields"> <v-checkbox v-model="myArray[item.code]" :label="item.name" ...

Unable to retrieve $_POST data using $.post requests while iterating through options with .each

Using the .each method, I constructed an options string and sent it via .post to an external script. clicked.closest("form").find("input,textarea").each(function(){ var input=$(this); if(index==1){ options = ...

The system considers the resource as a script, yet it was transmitted with the MIME type of text

I am encountering an issue when trying to integrate AngularJS/JavaScript into my HTML document. Each time I try to load my index.html file, the following error message appears: Resource interpreted as Script but transferred with MIME type text/html: "http ...

Issues with onClick events not triggering on transformed CSS3 elements

//My mind was completely tangled up. Everything is functioning properly, this question is inaccurate and outdated When I rotate an Element on the Y-axis and attempt to click on it, which has a bound eventListener (onClick), the event does not trigger (hov ...