Project 2: Unlimited Colors
This project demonstrates JavaScript's ability to change the background color of a web page every second, leveraging asynchronous functions. It showcases how we can control time-based events with JavaScript's setInterval
and clearInterval
methods.
HTML Overview
htmlCopy code<h1>Start should change the Background color every second</h1>
<button id="start">Start</button>
<button id="stop">Stop</button>
Key JavaScript Snippet:
javascriptCopy codelet intervalId;
document.getElementById('start').addEventListener('click', () => {
intervalId = setInterval(() => {
document.body.style.backgroundColor = `#${Math.floor(Math.random()*16777215).toString(16)}`;
}, 1000);
});
document.getElementById('stop').addEventListener('click', () => {
clearInterval(intervalId);
});
Key Concepts:
setInterval
: This function creates a loop that changes the background color every second. The non-blocking nature of JavaScript ensures that the page remains responsive while the color changes in the background.Random Color Generation: The expression
Math.floor(Math.random() * 16777215).toString(16)
generates a random hex color code every second. The use ofMath.random()
ensures unpredictable colors with each interval.clearInterval
: When the Stop button is clicked,clearInterval(intervalId)
halts the color change by clearing the active timer.
What’s New for a Programmer?
Asynchronous Control with
setInterval
: It allows you to execute code repeatedly without blocking the execution of other operations.Event Handling: Click events on the Start/Stop buttons are efficiently handled, demonstrating JavaScript’s power in real-time user interaction.
Explore the full code on my GitHub for more details!