Tips for preventing multiple button clicks until the completion of the initial click event

I created a clock that tells the time every quarter as per the professor's request. However, there is an issue - when I click multiple times, the clock keeps telling the time repeatedly until the number of tellings matches the number of clicks. I thought about making the button only function once. In HTML, I tried: <input= id="talkBTN" type="submit" value="Tell the time!" onclick=this.disabled>

Unfortunately, this approach didn't fully solve the problem as it simply prevented me from using the button.

This is the code for "tell the time". I believe I should utilize addEventListener and removeEventListener.

function tellTime(){
let currentTime = new Date();
timeWords.push("timeis");
numToWords(currentTime.getHours());
numToWords(currentTime.getMinutes());
console.log(timeWords);
timeTeller.addEventListener("ended", sayWords);
sayWords();
}



function sayWords(){
if (timeWords.length > 0) {
    timeTeller.src = soundURL + timeWords[0] + ".mp3";
    timeTeller.play();
    timeWords.shift();
    } else {
      timeTeller.removeEventListener("ended", sayWords);
      }
}

function numToWords(value){
if(value <= 20){
    timeWords.push(value);
    } else {
      let tens = Math.floor(value / 10);
      timeWords.push(tens * 10);
      if (value%10 != 0) {
          timeWords.push(value%10);
          }
    }
}

Answer №1

I haven't had the chance to fully implement this solution, so I can't guarantee its effectiveness in solving your issue. Have you considered utilizing a global variable as a potential solution?

var foo = false;

function tellTime(){
if (!foo) {
    let currentTime = new Date();
    timeWords.push("timeis");
    numToWords(currentTime.getHours());
    numToWords(currentTime.getMinutes());
    console.log(timeWords);
    timeTeller.addEventListener("ended", sayWords);
    sayWords();
    } else { // do something else }
}



function sayWords(){
if (timeWords.length > 0) {
    timeTeller.src = soundURL + timeWords[0] + ".mp3";
    timeTeller.play();
    timeWords.shift();
    } else {
      timeTeller.removeEventListener("ended", sayWords);
      }
foo = true
}

function numToWords(value){
if(value <= 20){
    timeWords.push(value);
    } else {
      let tens = Math.floor(value / 10);
      timeWords.push(tens * 10);
      if (value%10 != 0) {
          timeWords.push(value%10);
          }
    }
}

In the function that completes one round (perhaps sayWords), set the global variable to true.

The process flow would involve clicking the button, where the starter function checks the global variable - proceeding if it's off and turning it on. This cycle repeats until the final function changes the global variable back off.

Therefore, actions will only occur at the completion of the process.

Alternatively, you could toggle the button's disabled state using JavaScript. Similarly, disable the button at the start and re-enable it once the process is finished.

function tellTime(){
let btn = $('#btn').attr(“disabled”, true);
let currentTime = new Date();
timeWords.push("timeis");
numToWords(currentTime.getHours());
numToWords(currentTime.getMinutes());
console.log(timeWords);
timeTeller.addEventListener("ended", sayWords);
sayWords();
}



function sayWords(){
if (timeWords.length > 0) {
    timeTeller.src = soundURL + timeWords[0] + ".mp3";
    timeTeller.play();
    timeWords.shift();
    } else {
      timeTeller.removeEventListener("ended", sayWords);
      }
let btn = $('#btn').attr(“disabled”, false);
}

function numToWords(value){
if(value <= 20){
    timeWords.push(value);
    } else {
      let tens = Math.floor(value / 10);
      timeWords.push(tens * 10);
      if (value%10 != 0) {
          timeWords.push(value%10);
          }
    }
}

Does this explanation make sense to you?

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

A TypeError was encountered: Attempting to read the 'substr' property of an undefined variable

Recently, I encountered an issue while working on a script with jquery.min.js version 1.4. The problem arose when I had to upgrade the script to version 1.9.1. Uncaught TypeError: Can not read property 'substr' of undefined. I need assistance i ...

Is it possible to reverse the use of JQuery's .each() function without any additional plugins or modifications?

Similar Question: Reversing JQuery .each() Is there a better approach to using .each() in reverse? Currently, I am implementing it like this: var temp = []; $("#nav a").each(function() { temp.push($(this)); }); temp.reverse(); for(var i = 0; i ...

Successful Ajax Form Submission but Fails to Receive Response

I am currently working on a feature where users can select a record from a menu to delete it from the database. Below this menu, there is a table displaying all records from the database. Even though the record gets deleted and reflects in the table upon m ...

What is the best way to substitute multiple substrings with strings from multiple interconnected arrays?

Looking for a way to manipulate a lengthy string in JS? Seeking to add new characters to each match within the string to create a fresh output? Need to handle multiple occurrences of a specific substring in the long text? Any strategies or suggestions? con ...

Experiencing an excessive amount of re-renders

Encountering the error of too many re-renders Attempted to utilize useEffect to render only when weather changes function DashboardHeaderContent({ looks, weather }) { const [seasonRange, setSeasonRange] = React.useState(); function renderLook(look) ...

tap the hyperlink to complete the form and mimic the action of a designated

I'm working on an HTML form that includes a table and two submit buttons. <input type="image" name="button1" value="First Button" src="some_image.png"> <input type="image" name="button2" value="Second Button" src="some_image.png"> One ch ...

Testing if the App properly renders results in an error message: "No element found with the text: Profil"

I am struggling with testing Jest as I lack experience in this area. Specifically, I need to determine whether the App component is being rendered successfully. However, my test cases are failing. Upon checking the console log, I encountered the following ...

Creating a simulated RESTful backend using Sinon.js for an Angular.js project

In the process of developing my Angular.js application, I am incorporating RESTful services that utilize the $resource service. While this app will eventually connect to a Java Spring application, I am currently focusing on creating an isolated mock server ...

AngularJS Reload Scenario: A new way to refresh and enhance

My current project involves the development of a mobile app where I am retrieving data from a REST GET call. Everything is running smoothly. However, I would greatly appreciate expert advice on how to seamlessly re-render this data if the user decides to ...

Dynamic Node.js server constantly updating

My goal is to create a dynamic Node.js Express server that updates live, possibly by creating a specific route like /update to load a new configuration file. My concern is that the server could be in any state when the update occurs. It's possible tha ...

Despite implementing an event listener, the Google Maps API is failing to resize properly when created using AJAX

Currently, I am facing an issue with the Google Maps API as the map generated is not resizing to fit the div. Instead, it shows a large grey area which is quite frustrating for me. Can someone please assist me in resolving this problem? Below is the code ...

What could be causing my input box to act strangely when users attempt to input information?

I seem to be facing an unusual issue with the <input onChange={this.handleArticleId} value={this.props.articleIdValue} placeholder="article id"/> field. Whenever I try typing something, the letter only appears in the input box after clicking on the s ...

``After initialization, the service is unable to retrieve the object as

I have a special service that stores specific objects to be shared among different controllers. Here is an example of the code I am using: $rootScope.$on('controller.event', function(event, arg){ self.backendConnectorService.getBac ...

I am looking to add some flair to my ID "checkimg" using JavaScript

JavaScript if ((valid1 && valid2 && valid3 & valid4 && valid5 && valid6 && valid7 && valid8)==1) { // include an image in the specified ID. document.formElem.next1.disabled=false; } else { docume ...

Arrange the HTML DOM elements in the order of their appearance in a list

Is it possible to rearrange the order of <div> and its elements based on database information? For example, consider the following HTML structure: <div id="container"> <div id="A"> Form elements for A</div> <div id="B"& ...

What is the best way to navigate through a webpage to find a specific folder and show its contents on the page?

My goal is to design a webpage where users can browse their computer for a specific folder, select it, and have its content displayed on the webpage. I am fairly new to creating pages, but I want to develop a platform where you can easily find and view f ...

Obtaining JSON information within the AngularJS Scope

I am delving into the world of AngularJS for the first time and trying to understand it by following this example: http://jsfiddle.net/SAWsA/11/ After successfully acquiring data in JSON format, I encountered no issues. Here is a snippet of the JSON data: ...

Tips on customizing image borders/masks with hover effects

Is there a React library or a simple CSS trick to create an image's canvas cropping effect on hover? For example, similar to this: Thanks in advance! ...

The content inside a Textbox cannot be clicked on. I am seeking help with implementing JavaScript to enable it to be

As a newcomer in the world of programming, I am sharing a snippet of my JavaScript and HTML code with you. I am facing an issue where I want to enable users to start typing in a text box upon clicking on the text "User Name", without deleting any existing ...

Cannot utilize remote.require() in TypeScript due to compatibility issues

Recently, I've been facing a frustrating issue while developing an Electron application in TypeScript. I've been trying to execute a module from a renderer process using the code snippet below: import { remote } from 'electron' const ...