Is there a way in JavaScript to prevent a function from being executed when a button is clicked and instead

Is there a way to automatically stop changing the background color with random colors after a few seconds when clicking on a start button? I attempted using setTimeout() but my limited understanding of JavaScript has hindered me from finding a solution.

I would greatly appreciate it if someone could assist me in resolving this issue.

function setColor(randomColor){
  var body = document.body;
  body.style.backgroundColor=randomColor;
  var span = document.querySelector(".color");
  span.innerText = "\t"+randomColor;
}

function changeColor(){
  var randomColor = "#"+Math.floor(Math.random()*16777215).toString(16);
  setColor(randomColor);
}

const stopDisco = () => {
  var btn = document.querySelector("button");
  setColor("#ffffff");
}

function startDisco(){
  var btn = document.querySelector("button");
  changeColor();

  let interval =  setInterval(changeColor, 50);
    var stopBtn = document.querySelector(".stop")
    stopBtn.addEventListener('click', function () {
        clearInterval(interval);
        stopDisco();
    })
}
<body>
  <div>
  <button  class="on" onclick="startDisco()">Start Disco</button>
    <button class="stop">Stop Disco</button>
  <p>Hex Color:<span class ="color">#FFFFFF</span></p>
  </div>
</body>

Answer ā„–1

Here's an updated version

I incorporated a setTimeout function to end the process after a specified time

In addition, I have streamlined the definition of buttons and other elements for efficiency

const startBtn = document.getElementById("start");
const stopBtn = document.getElementById("stop");
const bodyElem = document.body;
const colorSpan = document.querySelector(".color");
let intervalID;

function setBackgroundColor(color) {
  bodyElem.style.backgroundColor = color;
  colorSpan.innerText = color; 
}

function changeBackgroundColor() {
  var randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16);
  setBackgroundColor(randomColor);
}

const stopDisco = () => {
  setBackgroundColor("#ffffff"); 
  clearInterval(intervalID); 
}

stopBtn.addEventListener('click', stopDisco);

startBtn.addEventListener('click', function() {
  clearInterval(intervalID);
  intervalID = setInterval(changeBackgroundColor,50);
  setTimeout(stopDisco,5000);
})
<body>
  <div>
    <button class="on" id="start">Start Disco</button>
    <button class="stop" id="stop">Stop Disco</button>
    <p>Hex Color:<span class="color">#FFFFFF</span></p>
  </div>
</body>

Answer ā„–2

To avoid adding an eventListener to the Stop button, a more efficient approach would be to utilize the setTimeout function to execute clearInterval() and stopDisco() methods. Here's how you can achieve this:

function changeColor(){
  var randomColor = "#"+Math.floor(Math.random()*16777215).toString(16);
  setColor(randomColor);
}

const stopDisco = () => {
  var btn = document.querySelector("button");
  setColor("#ffffff");
}

function startDisco(){
  changeColor();

  
  let interval =  setInterval(changeColor, 50);

  
  setTimeout(() => {
    clearInterval(interval);
    stopDisco();
  }, 3000); // Stops Disco after 3 seconds
}
<body>
  <div>
  <button  class="on" onclick="startDisco()">Start Disco</button>
    <button class="stop">Stop Disco</button>
  <p>Hex Color:<span class ="color">#FFFFFF</span></p>
  </div>
</body>

For further information, refer to the following MDN documentation:

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

Instructions for adding a select dropdown feature in Angular 6 that includes a search filter. Additionally, tips on how to filter objects by their name property

I need to add an auto-complete feature in my Angular 6 app where the data is displayed as objects in a dropdown and filtered as we type. **template.html** <mat-form-field > <input matInput [matAutocomplete]="auto" [formControl]="customerFi ...

Creating cookies in R Shiny: Storing variables for future use

Writing a fixed string to cookies can be done easily using methods like Cookies.set(\'cookie_2\', \'value\', { expires: 7 }) (see tutorial here). However, saving the variable user to cookie_2 may require a different ...

Unpredictable jQuery Ajax setTimeout

I have a script that retrieves data from ajax.php and displays it in a div. The intention is for the information to be shown for a period of 3 seconds before hiding the #ajax-content and displaying #welcome-content. Most of the time it works as intended, ...

Why do I keep getting undefined when I use React.useContext()?

I'm currently using Next.js and React, employing react hooks along with context to manage state within my application. Unfortunately, I've encountered a perplexing issue where React.useContext() is returning undefined even though I am certain tha ...

Upon introducing the CSS loader into the webpack configuration, TinyMCE unexpectedly ceases to function

My application development journey began with cloning code from https://github.com/DMPRoadmap/roadmap. This project is based on webpack and npm. To integrate select2, I executed npm install select 2 in the lib/assets directory. I aimed to incorporate a ...

Using React.js - What is the process for submitting a form automatically when the page loads?

Upon loading the page, I have a form that needs to be displayed. Here is the code snippet: <form name="myform" method="POST" className={classes.root} target="mydiv" action="https://example.com/submit" onLoad= ...

Having trouble uploading the file to Firebase storage

While attempting to upload files to Firebase using React, I encounter a perplexing issue. The file upload progress bar hits 100%, only to present me with an unfamiliar error message: { "error": { "code": 400, "message": "Bad Request. Could not c ...

Challenges with v-autocomplete in Vuetify.js

I am currently working with the v-autocomplete component and finding it somewhat rigid in terms of customization. I am hoping someone can provide some insight on this issue. Is there a way to have a default display text value in the input when the page fi ...

How can I use console.log to display a message when a variable reaches a specific value?

As a beginner coder, I am struggling to find the solution to this coding issue. Here is the code snippet that I have attempted: var X = "Angry"; if X = "Angry" console.log(X is Angry) After running this code, I encountered an error message specifically p ...

Using React.js to create a modal that includes ExpansionPanelDetails with a Checkbox feature

I am trying to achieve a specific visual effect with my code. Here is an example of the effect I want: https://i.stack.imgur.com/cJIxS.png However, the result I currently get looks like this: https://i.stack.imgur.com/547ND.png In the image provided, y ...

An error occurs when trying to load data into a grid upon clicking, resulting in an Uncaught TypeError: Unable to access properties of undefined (specifically 'dataState')

I have implemented a grid in React using a specific library, and I want to populate the grid with data fetched from an API call when the user clicks on a button labeled Fetch Products. However, I encounter an error during debugging: Uncaught (in promise) T ...

Receiving an `Invalid module name in augmentation` error is a common issue when using the DefaultTheme in Material

After following the guidelines outlined in the migration documentation (v4 to v5), I have implemented the changes in my theme: import { createTheme, Theme } from '@mui/material/styles' import { grey } from '@mui/material/colors' declar ...

How do I dynamically adjust class names for menu items as I scroll using jQuery?

I have a website with different sections identified by unique IDs, such as: <section id="home"> First Section </section> <section id="about_us"> Second Section </section> <section id="what_we_do&q ...

Having trouble adding global method using Plugin in Vue 3?

I have been working on creating a method that can generate local image URLs to be used in any template automatically. However, I encountered an issue while trying to develop a plugin that adds a global property. Plugin Implementation: // src/plugins/urlb ...

An easy guide to animating multiple sections of progress bars individually in Bootstrap

My Bootstrap code successfully animates a section of progress bars when the user views it. However, it currently animates all progress bars on the page rather than just those in the viewed section. This means that when the user moves to another section, th ...

Is it possible to retrieve the ID instead of the country name in the autocomplete feature?

I implemented Autocomplete from @Mui in my component const Profile = () => { const { register, handleSubmit, setValue, formState: { errors }, } = useForm({}); const [countries, setCountries] = useState([]); const submit = asyn ...

Syntax for private members in ES6 classes

I'm curious to know the most efficient way to declare private members within ES6 classes. In simpler terms, what is the best practice for implementing: function MyClass() { var privateFunction = function() { return 0; }; this.publicFuncti ...

"Add a pre-hook in mongoose to update a field in findOneAndUpdate by retrieving data from a

Iā€™m attempting to make modifications to a document in the findOneAndUpdate pre-hook. The code for this operation is provided below. userSchema.pre('findOneAndUpdate', function (next) { // this._update.$set //var user = new User(this._update.$s ...

Change the colors of a dynamic row in an HTML table using various options

I have successfully implemented a dynamic table using HTML and JavaScript. However, instead of applying alternate row colors, I want to assign a unique color to each row. How can I achieve this? <!DOCTYPE HTML> <html> <head> ...

A step-by-step guide on incorporating box-shadow for the jackColor in the Switchery Plugin

I am looking to add a box shadow to my iOS7 style switches for checkboxes when they are checked. Here is the code I have so far: var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function (html) { va ...