The command is executed repeatedly, but I would prefer it to only run once with each click

I'm currently working on developing a boxing or countdown timer. So far, I have managed to get it functioning and updating the div content successfully. However, I encountered an issue where adding a prompt caused the function to be called endlessly. Although I can observe the div being updated, it prevents the rest of my code from executing as intended. Any advice on how to overcome this obstacle would be greatly appreciated.

function timerStart() {
 let timerString = prompt("Enter Num");
 /*let timerString = document.getElementById("div0").textContent;*/
 let [minutes, seconds] = timerString.split(":").map(Number);

 if (seconds > 0) {
   seconds--;
   console.log(seconds);
 } else if (minutes > 0) {
   minutes--;
   seconds = 59;
   console.log(minutes);
 } else {
   clearInterval(intervalTime);
   return;
 }
 let newTimerString = `${minutes.toString().padStart(2, "0")}:${seconds
   .toString()
   .padStart(2, "0")}`;
 document.getElementById("div0").textContent = newTimerString;
}

function startTimer() {
 intervalTime = setInterval(timerStart, 1000);
}

document.getElementById("butt").addEventListener("click", startTimer);`

I attempted moving the prompt outside of the function, but that proved unsuccessful. Furthermore, trying to add a return statement at the end of the prompt function resulted in halting the entire process.

Answer №1

Create a new function that will display a prompt before initiating the interval. To transfer the time value between functions, global variables are being utilized.

var minutes, seconds

function timerStart() {

  if (seconds > 0) {
    seconds--;
    console.log(seconds);
  } else if (minutes > 0) {
    minutes--;
    seconds = 59;
    console.log(minutes);
  } else {
    clearInterval(intervalTime);
    return;
  }
  let newTimerString = `${minutes.toString().padStart(2, "0")}:${seconds
   .toString()
   .padStart(2, "0")}`;
  document.getElementById("div0").textContent = newTimerString;
}

function startTimer() {
  intervalTime = setInterval(timerStart, 1000);
}

function promptThenStartTimer() {
  let timerString = prompt("Enter Num");
  [minutes, seconds] = timerString.split(":").map(Number);
  startTimer()
}


document.getElementById("butt").addEventListener("click", promptThenStartTimer);
<button id="butt">click</button>
<div id="div0"></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

Possible rephrased version: "Encountering a Jquery clash

It appears that the issue causing my problem may be a Jquery conflict. Please correct me if I am wrong after reviewing the information below. I am new to Jquery and attempting to add a dropdown plugin to a website. The attempt is successful, but an existi ...

Transform Django Model Instance from Serialized Back to Object using Ajax

Currently, I'm utilizing Ajax to search for a model instance. Once found, I return that instance and pass it as a variable to a template tag within my template. To achieve this, in my view, I serialize the object before sending it to the Ajax success ...

Unusual glitch involving padding

Recently, I created a basic search application using React and incorporating Bootstrap's Grid system. However, I encountered an issue where the entire interface shifts to the left by approximately 10px when four or more products are rendered. https:/ ...

Inline-block list with consistent spacing between each item

I have a list of five items that are displayed inline. The challenge is to align the text in the first item with the left side and the text in the last item with the right side, while maintaining equal spacing between all items relative to both edges. Aft ...

What is the process of calling a function in my WordPress theme's functions.php file from an ajax handler?

I have a function in my theme's functions.php file that I'd like to execute using an ajax handler. An ajax handler is helpful for preventing the need to load the entire WordPress stack (including plugins) for each ajax request. functions.php f ...

Increase the date and time by a specified number of days

After searching for solutions on how to add a specific number of days to a given date, I came across various methods. However, my requirement is to add days to both Date and Time in the format MM-DD-YYYY HH:MM:SS. I attempted a method which worked fine wh ...

The checkbox in Yup does not get validated upon the user's submission

Below is the Yup configuration implemented in my React app: const schema = yup.object().shape({ email: yup.string() .email('E-mail is not valid!') .required('E-mail is required!'), password: yup ...

Retrieve information from the third section by utilizing ajax

My current setup involves: Having a form in form.php for inserting data, Displaying data in table format with pagination on display.php, and Using validation.js for validating form data along with the following function: $('#pagiCount a'). ...

Encountering this issue when setting up the forgot password functionality or trying to submit a POST request using Postman

Below is the code snippet related to resetting a password: exports.forgotPassword = async function(req, res, next) { //Check if user exists const user = await User.findOne({ email: req.body.email }) if (!user) { return next(new App ...

Leveraging the search feature within Google scripts to manipulate arrays

I'm facing a challenge in developing a function to search for regex in a cell and return a specific value if the result is found. The function works fine on an individual cell, but I can't seem to get it to work when applying it as an array to ce ...

Angular 6 provides a regular expression that specifically targets the removal of any characters that are not numbers and enforces the allowance of

I have tried various solutions to restrict input in an Angular material input box, but none seem to be effective for my specific case. I need the input field to only allow numbers and a decimal point. Any other characters should be automatically removed as ...

Declaring a sophisticated array as a property within another property in Typescript

As a newcomer to Angular and Typescript, I am facing a challenge while declaring a property with a complex array as one of its values. Here is what I have attempted: groupedItem: { customGroupId: string, cgName: string, category: [{ cu ...

angularslideables retro animation

I'm currently using the AngularSlideables library to toggle a modal within my Ionic project. You can check out a functional example in this fiddle: http://jsfiddle.net/3sVz8/19/ However, I am facing an issue where the initial height is set to 100% i ...

What steps should be taken to set up the datatable to sort records in descending order based on the creation date?

In my Rails application, I am utilizing the Datatable plugin to display data on the User index page. The first column in the index page is the created_at field, which displays dates like Mon, 17-Oct-16. I want to sort this column in descending order base ...

Placing elements in Chrome compared to IE

I'm currently attempting to position elements in two rows using mathematical calculations. One of the elements, thumb_container, is a div that is absolutely positioned. Within this container, I am dynamically loading and appending image thumbnails usi ...

Ensure that the text field in vue.js restricts input to integers and cannot be left empty

Trying to implement an input field in vue.js that only accepts integer values, ensures the quantity is not 0, and defaults to 1 if left empty. I attempted to block decimals with the code: <input type="number" min="1" @keydown="filterKey"></input& ...

Adjusting the demonstration of the d3 force-directed graph

Recently, I have started learning about javascript and D3.js, and I am eager to grasp their functionalities. My current focus is on experimenting with the force-directed graph example available at: http://bl.ocks.org/mbostock/4062045 My goal is to modify ...

Tips for creating a nodeCategoryProperty function for a TypeScript Model:

nodeCategoryProperty function has a signature requirement of (a: ObjectData, b?: string) => string. In my opinion, this should be updated to (a: ObjectData, b?: string) => string | void, as the function is intended to not return anything if used as a ...

What is the best way to set a default value for a password form input field?

I'm currently working on creating a form with input fields similar to those found on Twitter. I want to set default values for the input fields, which I have successfully done. However, when it comes to the password field, the default value is present ...

Transfer password securely through an ajax call

Is it secure to send a password through an Ajax request? I have a login box that makes an Ajax request to check the login credentials and receive a JSON Object with any errors. Would it be better to use form redirection instead? [EDIT] Storing the encry ...