Javacodepoint

Traffic signal light using Javascript

In this article, you will see the creation of a Traffic signal light using Javascript. Traffic lights, traffic signals, stoplights are signaling devices positioned at road intersections, pedestrian crossings, and other locations to control the flows of traffic.

To develop this application, we will use simple HTML, CSS, and Javascript. Basically, we are going to use setTimeout() and setInterval() methods of Javascript.

Traffic signal light using javascript

Table of Contents

How to make traffic light using Javascript?

It is very simple to create a traffic light application using javascript. Follow the below steps:

  • Write HTML Code
  • Write CSS Code
  • Write Javascript Code

1. HTML Code

Explanation:

  • We have defined three <div> for the green , yellow , and red color lights.
  • Putting all three lights into a container <div> defined with id="traffic-signal" .
  • Other two more <div> are defined with id="line1" and id="line2" for the stand of traffic lights.
  • Calling timer on body load to start traffic light.

2. CSS Code

Here we have defined the CSS for the above-defined HTML elements.

3. Javascript Code

  • We have defined a Timer(using setInterval() method) that will be called in every 12 seconds.
  • 12 seconds are divided for three lights ie. Green(5sec), Yellow(2sec), and Red(5sec).
  • We have defined a function startTrafficSignal() to show the specific light at the specified time.
  • We have used setTimeout() method inside startTrafficSignal() to show the specific light after specified milliseconds.
  • Here the logic for switching lights on and off is setting the css property opacity 1 and 0.3(1=on, .3=off).

Complete Code of Traffic light

Following is the complete code of Traffic light putting all HTML, CSS, and Javascript in a single file.

Preview and Live Demo

Traffic signal lights in javascript

Here you have seen how to create a Traffic signal light application using Javascript. We used setTimeout() and setInterval() method to develop it.

setTimeout() method basically we used for specific time delay and setInterval() method used to make a timer.

The CSS property called opacity has been used here to switch all three colors on and off.

Related Articles:

  • How to create a Stopwatch in JavaScript?
  • Accurate and Easy Stopwatch in JavaScript
  • How to Build a Bouncing Ball using JavaScript?

Leave a Comment Cancel Reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

TECH CHAMPION

Simple traffic light implementation using javascript.

In this article, I will illustrate a simple usage of JavaScript to display a Traffic Light Signal on the web page. This code demo can be used for implementing simple school and college projects. Also for novice JS Programmers, these sample codes will be useful.

The code example uses HTML/CSS and also basic bootstrap elements.

Traffic Signal Implementation using JavaScript

Requirements :.

The Traffic Signal should resemble the ones we see on our city roads and highways.

The Green signal should emit for 5 seconds, the Orange for 3 seconds, and the Red signal for 8 seconds.

When ON, RED should also display the text – STOP, Orange should display LOOK and Green should display GO.

When OFF, the texts should be slightly visible (just as we see painted texts labelled on the Signals).

Refer to the HTML clip above or the video below for more details.

Try to restrict using HTML,CSS/bootstrap and JavaScript only.

The below video will illustrate the requirement(In case the above HTML does not play due to browser issues).

I will only highlight the mechanics of the javascript part as the HTML design part is rather straightforward and self-explanatory. The main steps are summarized below.

  • The idea is to create HTML figures that would resemble the traffic signal. It should have three circles to represent the three different coloured lights.
  • Let there be three different css classes to style these circles differently based on colour codes. These coloured classes will represent the ON state of the lights as well. Let there be a fourth class (Blank class) to represent the OFF state (no light).
  • In order to switch ON a light, one would need to connect the element with the appropriate coloured class.
  • To switch OFF, replace the connection of the light from the coloured class to the BLANK class.
  • Create rectangles of appropriate dimensions to represent the outer container box, stand, and ground plate.
  • To keep the code approach simple for beginners, create three JS(javascript) functions – one for each light.
  • Each of these functions will associate the circle HTML elements with the coloured class and the corresponding text. It would also switch OFF the other two lights (replace their classes with BLANK class).
  • Use setTimeout to invoke these functions at different intervals so that they look to happen in sequence.
  • Wrap all three functions using the setInterval function so that the entire operation happens continuously so as to mimic a live traffic light operation.

Below is the HTML code for TrafficLight.html. There is not much to explain on the HTML part. The contextual code uses css class to generate coloured rectangles and circles.

The css file (C:\Users\IDEAPAD\Desktop\temp\TrafficSignal.css) contents is as below. One can use any layout design at his or her convenience. The below code is for ready reference to use.

The below snippet contains the JS part. The css styling code has 4 classes of circles. All of these 4 circle classes are the same but with different layout colours (red, green, orange and black for empty blank or OFF state).

Each of the coloured classes represents the ON state while the BLANK class represents the OFF state. The mechanics to switch between ON and OFF states is to simply use JS (DOM) code to replace the class of the circles from the coloured (ON) state to the BLANK(OFF) state.

The Javascript simply replaces the light circles one by one with the OFF state class at intervals. This entire cycle is repeated infinitely using the setInterval function.

To introduce gaps between lights ON state, we can make use of the setTimeout function.

There are three user-defined functions, one for each color of light. Each function switches On the corresponding light (along with the labeling of the text) and switches OFF the other two.

NOTE: In the above code, the green light function will trigger first, then at 5th second (5000 ms), the orange light function will trigger, and at 8th second (8000ms) red light function will trigger. The entire cycle will be repeated every 13th second(13000 ms).

So, green will light for 5 seconds, orange for 3 seconds (8-5), red for again 5 seconds ( 13 – 8).

article writing software

Hi there this is somewhat of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding skills so I wanted to get guidance from someone with experience. Any help would be enormously appreciated!

Submit a Comment Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Notify me of follow-up comments by email.

Notify me of new posts by email.

Submit Comment

RELATED POSTS

Coloured Squares using Simple Canvas element in Javascript

Coloured Squares <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Coloured Squares</title> </head> <body> <!-- Create a display canvas on the page --> <div align="center"> <canvas id="cnv1" width="500px"...

Javascript Code for colour-changing boxes

The HTML/Javascript code in this sample generates a set of 4 squares (canvases) and changes their color every second. Color Changing Boxes START STOP <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Color Changing...

Javascript code to change inner HTML and Style

A simple JavaScript code to illustrate the text content and colour change <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Sample1</title> </head> <body> <h1>JavaScript Sample Code</h1> <p id="para1"...

LATEST POSTS

9 Interview Red Flags You Should Never Ignore

9 Interview Red Flags You Should Never Ignore

Uncover 9 common interview red flags that can reveal a toxic workplace or unfair treatment, saving you from costly mistakes.

Essential Tools for Database Production Support

Essential Tools for Database Production Support

Discover essential tools for database production support, including monitoring, performance tuning, backups, and security. Enhance efficiency and reliability.

Operational Monitoring for System Performance

Operational Monitoring for System Performance

Operational monitoring of system performance optimizes configurations and prepares for issues with key metrics.

Achieving Optimal System Performance Through Effective Tuning

Achieving Optimal System Performance Through Effective Tuning

Learn effective system performance tuning strategies to improve response time, throughput, and resource use tailored to application needs.

ChatGPT and the Rise of Large Language Models

ChatGPT and the Rise of Large Language Models

Discover the power of large language models like ChatGPT and their impact on AI, revolutionizing information interaction.

Decoding Google’s Lucrative Offer: Is 1.64 Crore Salary for 10 Years of Experience Really ‘Crazy’?

Decoding Google’s Lucrative Offer: Is 1.64 Crore Salary for 10 Years of Experience Really ‘Crazy’?

Google’s Lucrative Offer: Is 1.64 crore salary for 10 years of experience ‘crazy’ or standard? We delve into the details and analyze the offer.

Understanding the Conversion: How Many Kilograms Are in 1 Tonne?

Understanding the Conversion: How Many Kilograms Are in 1 Tonne?

Discover the simple conversion of kilograms to tonnes, crucial for shipping, construction, and more!

Windows 11 Update Issues: KB5043145 Causing Chaos

Windows 11 Update Issues: KB5043145 Causing Chaos

MICROSOFT WINDOWS

Windows 11 Update Issues: KB5043145 causing chaos for users with unexpected bugs. Learn how to avoid these problems.

Unveiling the Secrets of Dreams: Exploring Dream Recording Devices

Unveiling the Secrets of Dreams: Exploring Dream Recording Devices

Learn about dream recording devices and their potential benefits for understanding our thoughts and emotions.

WhatsApp Messages: The Art of Connecting Without Saving Numbers

WhatsApp Messages: The Art of Connecting Without Saving Numbers

Master the art of WhatsApp messaging without saving numbers. Explore 5 clever methods, from direct links to app integrations.

  • Print Friendly

Building a Traffic Lights System with JavaScript

JavaScript

Introduction

Set up the project structure, implement the red light function, implement the green light function, call the traffic lights functions, test the traffic lights.

In this project, you will learn how to create a traffic lights system that changes the color of the light from red to green after a certain time interval. This project will help you understand the basics of JavaScript and how to manipulate the DOM to display different elements based on time-based events.

In this project, you will learn:

  • How to set up a basic HTML and JavaScript project structure
  • How to implement a function to change the display of the traffic light to red after 3 seconds
  • How to implement a function to change the display of the traffic light to green after 6 seconds
  • How to coordinate the execution of the red and green light functions using async/await
  • How to test the traffic lights system and ensure it works as expected

🏆 Achievements

After completing this project, you will be able to:

  • Manipulate the DOM using JavaScript to change the display of HTML elements
  • Use setTimeout() to schedule time-based events
  • Manage asynchronous operations with async/await
  • Test and debug your JavaScript code

Skills Graph

In this step, you will set up the project structure and prepare the necessary files and folders.

  • Open the editor. You should see index.html , trafficlights.js and a few image files in the /home/labex/project directory.
  • Click on Go Live button in the bottom right corner of WebIDE, to run the project.
  • Open "Web 8080" on the top of the VM and refresh it manually and you will see the page.

unfinished

In this step, you will implement the function to change the light to red.

  • In the trafficlights.js file, locate the red() function.
  • Set a variable above the red function and give the initial value:
  • The red() function should change the display of the default light to none and the display of the red light to inline-block after 3 seconds.

In this step, you will implement the function to change the light to green.

  • In the trafficlights.js file, locate the green() function.
  • The green() function should change the display of the red light to none and the display of the green light to inline-block after 3 seconds (6 seconds after the page load).

In this step, you will call the trafficlights() function to start the traffic lights sequence.

  • In the trafficlights.js file, locate the trafficlights() function.
  • The trafficlights() function should call the red() and green() functions in sequence using the async/await syntax.
  • Save the changes to the trafficlights.js file.
  • Refresh the page in your browser. You should see the traffic lights change from the default light to red, and then to green after 6 seconds. The finished result is as follows:

Congratulations! You have completed the Colour Changeable Light project. If you have any questions or need further assistance, feel free to ask.

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like

  • Building a Web Avoiding Block Game
  • Creating a Minesweeper Game with JavaScript
  • jQuery Flip Puzzle Game
  • Interactive Film Collection Web App
  • Fruit Matching Game with HTML, CSS, JavaScript
  • Initialize N-Dimensional Array
  • Insert Value at Array Index
  • Insertion Index in Sorted Array
  • Implementing Insertion Sort in JavaScript
  • String Is Alphanumeric

Quick Start with JavaScript

Quick Start with JavaScript

Build an VSCode Extension With ChatGPT

Build an VSCode Extension With ChatGPT

Build a Tic-Tac-Toe Web App

Build a Tic-Tac-Toe Web App

We use cookies for a number of reasons, such as keeping the website reliable and secure, to improve your experience on our website and to see how you interact with it. By accepting, you agree to our use of such cookies. Privacy Policy

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings
  • Full Stack Course
  • React Native
  • CSS Frameworks
  • JS Frameworks
  • Web Development

Design a Traffic Light Animation using HTML and CSS

In this article, we will explore how HTML and CSS can be utilized to create a Traffic signal animation with Red, Green, and Yellow colors. In this, we have written a code that produces a live traffic signal using HTML and CSS. The code is responsive and uses “Keyframes” for better animation control.

Screenshot-2023-11-17-152740

  • First, create three divs inside the container div for three signal lights.
  • Use CSS to define the colors for each light (red, yellow, green).
  • Align the signals in the center of the webpage.
  • Utilize CSS keyframe animations to create the blinking effect for lights.

Example: In this example, we will see the basic implementation to create a traffic signal static website by using HTML, and CSS.

                                   

Similar Reads

  • Geeks Premier League
  • Web Technologies
  • Web Templates
  • Geeks Premier League 2023

Please Login to comment...

  • PS5 Digital vs. Disc : Which PlayStation 5 Should You Buy in 2024?
  • AMD vs. Nvidia Graphics Cards 2024: Which GPU Should You Choose?
  • Top IPTV-Anbieter in Ă–sterreich fĂĽr gĂĽnstiges Streaming in 2024
  • IPTV Austria: Top 10 IPTV Subscription Providers for Austrian and International Channels
  • GeeksforGeeks Practice - Leading Online Coding Platform

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Staging Ground badges

Earn badges by improving or asking questions in Staging Ground.

Automatic traffic light sequence Javascript

I have tried many methods in order to get this to work however I just cant seem to get the image to change automatically in a set time, the code is:

Donald Duck's user avatar

  • those file names are containing a whitespace. You should never use whitespaces in file names and you missed ' ' it should be getElementById('light') –  cyr_x Commented Mar 3, 2017 at 12:55

2 Answers 2

There is an error here:

Also note when your image changes you will loose the path in the image src property as they are not included in the array of lights.

uzr's user avatar

To be honest, i wonder if the result is supposed to be just visual, or it has to be also "functional"... You could solve this visually simply by using GIF (yea, not the greatest), or via CSS - not an answer to your question per se. But it might be useful to know your options.

@keyframes red { 0% {background: red;} 33% {background: red;} 34% {background: black;} 100% {background: black;} } @keyframes yellow { 0% {background: black;} 33% {background: black;} 34% {background: yellow;} 66% {background: yellow;} 67% {background: black;} 100% {background: black;} } @keyframes green { 0% {background: black;} 66% {background: black;} 67% {background: green;} 100% {background: green;} } .trafficLight { height: 120px; width: 40px; padding:3px; background:#CCC; } .trafficLight div { width: 90%; height: 30%; margin:7% auto; border-radius: 50%; animation-duration: 5s; animation-iteration-count: infinite; } .red {animation-name: red;} .yellow {animation-name: yellow;} .green {animation-name: green;} .trafficLight, .trafficLight div{ box-shadow:inset 5px 5px 5px rgba(255,255,255,.5), inset -5px -5px 5px rgba(0,0,0,.5); } <div class="trafficLight"> <div class="red"></div> <div class="yellow"></div> <div class="green"></div> </div>

Adam K.'s user avatar

  • Fun fact: This whole animation is approx 0.9KB large. Scalable without any loss of detail. –  Adam K. Commented Mar 3, 2017 at 13:55
  • it has to be with pictures and not a gif, I know there are easier ways to achieve the same thing but we are not allowed to use a gif or CSS. –  Ryan Anderson Commented Mar 5, 2017 at 15:19

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript html or ask your own question .

  • The Overflow Blog
  • Rust is evolving from system-level language to UI and frontend development
  • Is this the real life? Training autonomous cars with simulations
  • Featured on Meta
  • Preventing unauthorized automated access to the network
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Feedback Requested: How do you use the tagged questions page?
  • Proposed designs to update the homepage for logged-in users

Hot Network Questions

  • Does Wigner rotation mean that in special relativity it is possible to rotate an object without applying any torque to it?
  • Did 60 Minutes edit one of Kamala Harris' interview answers?
  • Travelling as a dual national (UK and Denmark) from Denmark to Australia - which passport should I use?
  • How to find the name of the binary used to launch an application installed with pacman?
  • Successive divisions in a list
  • Flattening so that only pairs remain
  • Travelling to the US for research under VWP/B
  • Why do evangelicals interpret Heb 4:12 with a meaning that ascribes animacy and agency to a bunch of words?
  • Are stances very robust or very fragile?
  • Mexican Hat Challenge, #メキシカンハットチャレンジ
  • Could an automotive 24V/10A relay without a flyback diode be burned out?
  • Did Kamala Harris withhold evidence in a capital case?
  • Is "swabbed in dirty robes" a valid expression?
  • Can the temperature around a thermal cube exceed 95 degrees?
  • Old anime with a robot-like creature who had to absorb the male main character to use most of its abilities
  • A novel about an object from space crossing the solar system and found out not to be an asteroid but a spaceship. Not Greg Bear's Eon
  • Where can I find a list of all zugzwang positions with ≤ 5 pieces?
  • My head seems to have fallen off
  • Homeowners insurance requiring auto Insurance
  • What was the poison gas created in "Armadale" by Wilkie Collins?
  • Meaning of the joke A: "how much coke do you do" B: "Yes."
  • String extraction does not work on dynamically generated string
  • When half-elves have children their lives are drastically shortened. What's the formula for calculating it?
  • Probability of Tyrion and Cersei Sitting Together at a Round Table

traffic light in javascript assignment expert

COMMENTS

  1. Traffic signal light using Javascript

    Explanation: We have defined a Timer(using setInterval() method) that will be called in every 12 seconds.; 12 seconds are divided for three lights ie. Green(5sec), Yellow(2sec), and Red(5sec). We have defined a function startTrafficSignal() to show the specific light at the specified time.; We have used setTimeout() method inside startTrafficSignal() to show the specific light after specified ...

  2. html

    Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Visit the blog

  3. GA Section 2

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.

  4. JavaScript

    #javascript #codingpractice #traficlight #colorpicker JavaScript | Coding Practice 1 | Traffic Light | Color Picker | NxtWave | CCBP | JS by Soumya BTechLear...

  5. Simple Traffic Light implementation using Javascript

    The Traffic Signal should resemble the ones we see on our city roads and highways. The Green signal should emit for 5 seconds, the Orange for 3 seconds, and the Red signal for 8 seconds. When ON, RED should also display the text - STOP, Orange should display LOOK and Green should display GO. When OFF, the texts should be slightly visible ...

  6. Traffic Lights System

    Test the Traffic Lights. Save the changes to the trafficlights.js file. Refresh the page in your browser. You should see the traffic lights change from the default light to red, and then to green after 6 seconds. The finished result is as follows: Congratulations! You have completed the Colour Changeable Light project.

  7. GitHub

    [] The state of a traffic light should go in the following order and repeat indefinitely Red, Green, Yellow; If the color is red, and you click nextState, the light should change to green; If the color is green, and you click nextState, the light should change to yellow; If the color is yellow, and you click nextState, the light should change to red [] The correct circle should correspond with ...

  8. traffic-light-js/README.md at master · gaebar/traffic-light-js

    GA Section 2 - Complete the 'Traffic Light' Javascript exercise - traffic-light-js/README.md at master · gaebar/traffic-light-js

  9. Traffic Light JS Exercise

    Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself. If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.

  10. Traffic Light

    See an example of how to use techniques including bitwise logic and arrays to create a JavaScript model of a traffic light.

  11. Traffic light using HTML CSS Javascript.

    Traffic light simulator using CSS3, HTML, Javascript. ... Traffic light simulator using CSS3, HTML, Javascript. ... Pen Settings. HTML CSS JS Behavior Editor HTML. HTML Preprocessor About HTML Preprocessors. HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read ...

  12. Traffic Light CSS

    A simple traffic light with pure CSS. JQuery-Javascript added to change the lights on click. ... Pen Settings. HTML CSS JS Behavior Editor HTML. HTML Preprocessor About HTML Preprocessors. HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents ...

  13. Design a Traffic Light Animation using HTML and CSS

    First, create three divs inside the container div for three signal lights. Use CSS to define the colors for each light (red, yellow, green). Align the signals in the center of the webpage. Utilize CSS keyframe animations to create the blinking effect for lights. Example: In this example, we will see the basic implementation to create a traffic ...

  14. Traffic Light Exercise with React Class Components

    In this video, we build a Traffic Light in React using Class based components in order to compare the code to the previous video's code and show the differen...

  15. Traffic Light

    Traffic Light | Coding Practice 1 | Introduction to JS & Variables | Build Your Own Dynamic Web Application | NxtWave | ccbp 4.o

  16. javascript

    I am trying to make traffic lights using html and JavaScript, I am writing it in notepad and converting it to a html file when in save it, my code only shows the outside box, please help &lt;!DOCT...

  17. Traffic Light JS

    Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself. If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.

  18. Automatic traffic light sequence Javascript

    document.getElementById('light').src = list[index]; // Needs '' Also note when your image changes you will loose the path in the image src property as they are not included in the array of lights. Also