What steps can I take to implement automation for this traffic light sequence?

document.getElementById('SwitchButton').onclick = automateLights;

function turnOnRedLight() {
  clearAllLights();
  document.getElementById('stopLight').style.backgroundColor = "red";
}

function turnOnOrangeLight() {
  clearAllLights();
  document.getElementById('slowLight').style.backgroundColor = "orange";
}

function turnOnGreenLight() {
  clearAllLights();
  document.getElementById('goLight').style.backgroundColor = "green";
}

function turnOnRedAndOrangeLights() {
  clearAllLights();
  document.getElementById('stopLight').style.backgroundColor = "red";
  document.getElementById('slowLight').style.backgroundColor = "orange";
}

function clearAllLights() {
  document.getElementById('stopLight').style.backgroundColor = "black";
  document.getElementById('slowLight').style.backgroundColor = "black";
  document.getElementById('goLight').style.backgroundColor = "black";
}

var buttonClicks = 0;
var loop = true;

function automateLights() {
  buttonClicks++;
  switch (buttonClicks) {
    case 1:
      clearAllLights();
      document.getElementById('stopLight').style.backgroundColor = "red";
      break;
    case 2:
      clearAllLights();
      document.getElementById('stopLight').style.backgroundColor = "red";
      document.getElementById('slowLight').style.backgroundColor = "orange";
      break;
    case 3:
      clearAllLights();
      document.getElementById('goLight').style.backgroundColor = "green";
      break;
    default:
      break;
  }
}
body {
  font-family: sans-serif;
}
#controlPanel {
  float: left;
  padding-top: 30px;
}
.button {
  background-color: gray;
  color: white;
  border-radius: 10px;
  padding: 20px;
  text-align: center;
  margin: 90px 40px;
  cursor: pointer;
}
#traffic-light {
  height: 550px;
  width: 200px;
  float: left;
  background-color: #333;
  border-radius: 40px;
  margin: 30px 0;
  padding: 20px;
}
.bulb {
  height: 150px;
  width: 150px;
  background-color: #111;
  border-radius: 50%;
  margin: 25px auto;
  transition: background 500ms;
}
<div id="controlPanel">
  <h1 id="SwitchButton" class="button">Automate Lights</h1>
</div>
<div id="traffic-light">
  <div id="stopLight" class="bulb"></div>
  <div id="slowLight" class="bulb"></div>
  <div id="goLight" class="bulb"></div>
</div>

Hello! I have created a traffic light sequence that can be automated with the press of a single button. The lights will change from red to orange to green in a cycle when the button is clicked. Feel free to ask any questions or suggestions on how to improve this automation feature. Thank you for your time!

Answer №1

To implement the functionality discussed in the comments, utilizing setInterval is the way to go. I have crafted an example code snippet below to showcase this concept in action. Additionally, I have encapsulated the lights within objects for a more streamlined approach.

/*
  Light object for better organization
*/
function Light(color, element) {
  this.color = color;
  this.element = document.getElementById(element);
}
Light.prototype = {
  on: function() {
    this.element.style.backgroundColor = this.color;
  },
  off: function() {
    this.element.style.backgroundColor = "black";
  }
}

/*
Initialization
*/
var lights = [new Light("green", "goLight"),
  new Light("orange", "slowLight"),
  new Light("red", "stopLight")
];

var sequence = [["green"],["green", "orange"],["red"]],
    position = 0,
    timer = null;

var go = document.getElementById("go"),
  stop = document.getElementById("stop");

go.onclick = function() {
  clearTimeout(timer);
  timer = setInterval(function() {

    lights.forEach(function(light) {
      if (sequence[position].indexOf(light.color) > -1) light.on();
      else light.off();
    });
    
     if (position++ >= sequence.length-1) position = 0;
   

  }, 2000);
}
stop.onclick = function() {
  clearTimeout(timer);
}
 body {
      font-family: sans-serif;
}

      #controlPanel {
      float: left;
      padding-top: 30px;
}

      .button {
      background-color: gray;
      color: white;
      border-radius: 10px;
      padding: 20px;
      text-align: center;
      margin: 90px 40px;
      cursor: pointer;
}

      #traffic-light {
     height: 550px;
      width: 200px;
      float: left;
      background-color: #333;
      border-radius: 40px;
      margin: 30px 0;
      padding: 20px;
}

      .bulb {
     height: 150px;
      width: 150px;
      background-color: #111;
      border-radius: 50%;
      margin: 25px auto;
      transition: background 500ms;
} 
    <div id="controlPanel">
        <h1 id="go" class="button">Go</h1>
        <h1 id="stop" class="button">Stop</h1>
    </div>
        <div id="traffic-light">
        <div id="stopLight" class="bulb"></div>
        <div id="slowLight" class="bulb"></div>
        <div id="goLight" class="bulb"></div>
    </div>

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

Updating the positions of Mesh objects in Three.js asynchronously

I'm currently working on a Three.js application where I am creating a grid to display various objects. These objects are rendered on the grid based on their positions, which are obtained from data fetched from a REST API that I poll every 300 millisec ...

Unable to cancel the RTK query request

It's quite a dilemma. I need to handle the request differently when there is no user present. I've attempted different approaches like this and that const { data: carts = [] as ICart[], isFetching } = api.useGetCartProductsQuery(user.id, { skip: ...

Implementing meta tags in React.js

I am attempting to incorporate dynamic meta-tags on each page of my website. However, despite my efforts, I cannot seem to locate the meta-tags in the page's source code. Do I need to make adjustments in public/index.html, considering that I am not ut ...

Ways to determine if a website is being accessed from a mobile device or a computer without relying on TeraWurfl technology

After my search on the internet yielded no answers, I decided to post my question here. Is there a method available to detect whether a site is being accessed from a computer or mobile device without using TeraWurfl? I'm looking for a simple code snip ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

Executing a javascript function from an ajax-loaded webpage

I have a form where I upload a file using an ajax call that includes an API request. Once the API call is successful, I need to update a table displaying the list of uploaded files. Initially, I attempted calling a JavaScript function within the ajax page, ...

Determine the state of the checkbox property in HTML

Is there a way to conditionally set the checked property of a checkbox? In my application, I have checkboxes for each row. The database includes a column 'IsSaved' with values of either 0 or 1. If 'IsSaved' is 1 for a particular row, I ...

The perplexity surrounding the functionality of th and tr tags is causing confusion in

Below is the code snippet I have in my HTML table. <table> <tbody> <thead> <tr> <th align="right" colspan="4"> <span class="font-style-bold">SCHEDULE OF RATES</span> ...

The query pertaining to Facebook redirect functionality

I have a Facebook ad with a URL encoded in it, and I need to extract the final destination URL that it redirects to using JavaScript in my Python program. The standard urllib2/mechanize methods don't work because of the JavaScript involved, and as a P ...

An unknown browserLink expression was encountered

I encountered an issue with " browserLink " that you can see below <div ng-show="optList.editing && optList.BANKRUPT_FLG != 'Y' && (optList.OPT != 'TF' || (optList.OPT == 'TF' && optLi ...

In JavaScript, use a regular expression to replace all instances of %2F with %

Looking for a JavaScript/regex solution to transform %2F into %21. This will allow me to successfully pass forward slashes through a GET parameter after using encodeURIComponent() on a URL. Once the data reaches the server, I'll convert back from ! ...

Issue with loading contentsCss in CKEDITOR with VUEJS2

Currently in the process of developing a website using Vue.js 2, we incorporated the ckeditor4-vue plugin some time ago. An issue has recently come up regarding the font not matching the rest of the application. The preference is to default to 'Lato& ...

Is there a way to remove specific items from my array in Vue.js?

Essentially, I am using an HTML select element that is populated with arrays of registered users. <label > <b> <i style="opacity:0.8">Users:</i> </b> </label>&nbsp;&nbsp; <select class=&quo ...

How to iteratively process JSON array using JavaScript?

I am currently attempting to iterate through the JSON array provided below: { "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "<a href="/cdn-cgi/l/email-pro ...

Interacting with YouTube Data API without requiring user input

I'm currently developing a music website that enables users to create YouTube playlists. Initially, I experimented with JavaScript: https://developers.google.com/youtube/v3/code_samples/javascript The procedure involves an initial authorization ste ...

Using jQuery to extract a specific portion of a URL path

Seeking assistance with extracting category information from lengthy URLs and assigning it to a variable. Consider the following URL: http://example.com/community/home/whatever.html The goal is to assign the variable to the folder path that follows /hom ...

How can I limit the keys in a Typescript object to only certain strings?

Is there a way in Typescript to create an object of type Partial with keys that can only be a combination of 'a', 'b', or 'c'? The object should not have all 3 keys, but it must have at least one. Here's what I've at ...

Prevent background element from being selected with a double-click

Whenever I double-click on the background, the first element gets selected. How can I prevent this from happening? Here is a fiddle to demonstrate: https://jsfiddle.net/cb6fjr7n/1/ <input style="text" value="lala"/> If you double-click outside of ...

Unraveling encrypted data with CryptoJs in MVC: A guide to decrypting values in code behind

I am currently developing an MVC application where I am working on encrypting my password. I have successfully encrypted the password using a click event and it is functioning properly. However, I am now facing the challenge of decrypting the same value in ...

Can JavaScript functions be automated on a web browser using Power BI tables?

I am facing a challenge with saving data from a powerbi table on a daily basis. When I hover over the table and click on the ellipsis menu, a button element is generated in HTML that allows me to save the data to a CSV file using Selenium. However, achiev ...