The functionality of the button in my script is limited to a single use

Below is a simple code snippet that I wrote:

  • HTML & CSS:
<!DOCTYPE html>
<html>
    <head>
        <title> JavaScript Console </title>
        <style>
            button { text-align:center;
                     width:200px;
                     height:30px;
                     font-size:17px;
                     font-family:courier new;
                     border:solid 2px black;
                     font-weight: bold;
                     background-color:lightblue; 
                     cursor:pointer;
                     border-radius: 20px;
                     transition: 0.5s; 
                    }

            button:hover {
                          transform: scale(1.2, 1.2);
                          font-size:19px;
                          background-color: cyan;
                    }
        </style>
    </head>
    <body style="text-align:center">
        <fieldset>
        <legend style="text-align:center;margin-bottom: -20px"><h1 id="h1" style="text-align:center;">JavaScript tests on console</h1></legend>
        <p style="color:green;"> Have fun coding !</p>
        <br/> 
        <div style="text-align: center;"><button id="btn" onClick="buttonHandler()" >Show time</button></div>
        <p id="time" style="color:blue;"></p>
        <p id="tick" style="color:red;"></p>
        <p></p>
    </fieldset>
        <script src="./test.js"></script>
    </body>
</html>
  • JavaScript:
console.log('Console is working fine !'); 

/**********************************************************************/
var x = 60;
function tick() {
    var date = new Date();
    document.getElementById("time").innerHTML = date;
    x--;
    document.getElementById('tick').innerHTML = `The time will be hidden after ${x} seconds`;

}

function clearAll(id) {
    window.clearInterval(id);
    document.getElementById('time').style.display = "none";
    document.getElementById('tick').style.display = "none";
}

function buttonHandler(e) {
    var id = window.setInterval(tick,1000);

    setTimeout(()=> clearAll(id),60000);

}

/**********************************************************************/

The issue I'm facing is that the 'Show time' button only works for the first click and doesn't work again after that.

I believe the problem lies with the setInterval() method which runs only once, but I'm not sure how to resolve it.

Could someone provide guidance on how to fix this issue?

Answer №1

You may notice that the element is hidden at the end of the timer within the clearAll function:

document.getElementById('time').style.display = "none";
document.getElementById('tick').style.display = "none";

To make them visible again, you need to display them once more upon clicking.

If the button is clicked multiple times, the tick function will be executed repeatedly, causing the timer to decrement faster.

I have added a safeguard to prevent running the function multiple times and resetting the timer.

console.log('The console is functioning correctly!'); 

/**********************************************************************/
var x = 60;
var isRunning = false;

function tick() {
    var date = new Date();
    document.getElementById("time").innerHTML = date;
    x--;
    document.getElementById('tick').innerHTML = `The time will disappear in ${x} seconds`;
}

function clearAll(id) {
    window.clearInterval(id);
    document.getElementById('time').style.display = "none";
    document.getElementById('tick').style.display = "none";
    isRunning = false;
}

function buttonHandler(e) {
    if (isRunning === false) { // To avoid multiple clicks triggering tick function
        isRunning = true;
        x = 60; // Reset timer
        document.getElementById('time').style.display = "block"; // Make visible again
        document.getElementById('tick').style.display = "block"; // Make visible again
        var id = window.setInterval(tick,1000);

        setTimeout(()=> clearAll(id),60000);
    }
}

/**********************************************************************/
<!DOCTYPE html>
<html>
    <head>
        <title> JavaScript Console </title>
        <style>
            button { text-align:center;
                     width:200px;
                     height:30px;
                     font-size:17px;
                     font-family:courier new;
                     border:solid 2px black;
                     font-weight: bold;
                     background-color:lightblue; 
                     cursor:pointer;
                     border-radius: 20px;
                     transition: 0.5s; 
                    }

            button:hover {
                          transform: scale(1.2, 1.2);
                          font-size:19px;
                          background-color: cyan;
                    }
        </style>
    </head>
    <body style="text-align:center">
        <fieldset>
        <legend style="text-align:center;margin-bottom: -20px"><h1 id="h1" style="text-align:center;">JavaScript Console Tests</h1></legend>
        <p style="color:green;"> Enjoy coding!</p>
        <br/> 
        <div style="text-align: center;"><button id="btn" onClick="buttonHandler()" >Show Time</button></div>
        <p id="time" style="color:blue;"></p>
        <p id="tick" style="color:red;"></p>
        <p></p>
    </fieldset>
        <script src="./test.js"></script>
    </body>
</html>

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

Building a row of five dynamic columns using Bootstrap's responsive design

I'm looking to set up a row with 5 responsive columns that have equal padding on all sides, but I'm struggling to find the best way to do this using Bootstrap. Here's my current HTML: <div class="row five-col-row"> < ...

How is it possible for me to retrieve data values directly from a sequelize model?

My question is straightforward - when doing a single select in sequelize, a model is returned. Inspecting this model reveals various options such as dataValues, _prevValues, _change, _options, isNewRecord, and more. What puzzles me is that you can also a ...

When comparing strings, if they match, replace them with bold text

Today, I faced a challenging brain teaser that kept me occupied for over an hour. The task at hand is to compare two strings: the text input from the field and data-row-internalnumber. The goal is to determine if they match and then bold only the last let ...

Target only the <a> elements within a specific <div> using JavaScript

How can I target the first occurrence of the letter 'a' in this code using JavaScript? (href=some.php) <div class="accordionButton"><div id="acr_btn_title"><a href="some.php"><p>stuff</p></a></div><di ...

Tips for saving a value within a jQuery function for future use in a different function

I have a situation where I receive a value from a jQuery function that I need to pass to another function. How can I achieve this? jQuery.getJSON(url+"&startDate="+startDate+"&endDate="+endDate+"&jobId="+jobId+"&type="+type, function(data) ...

Error: Attempting to access the 'map' property of an undefined variable, cart

My project consists of two main components, App.js and Cart.js. I am utilizing material-ui and commerce.js API for this application. import React , {useState , useEffect} from 'react' import Products from './Components/Products/Products&apos ...

Finding your site's First Contentful Paint (FCP) can be done by analyzing the

After doing some research on Google insights, I came across information about FCP. However, I'm still unsure about how to determine my site's FCP and other relevant metrics. If anyone could provide me with more information or share detailed link ...

How can you toggle the visibility of a text based on the selection of a jQuery radio button?

Is it possible to dynamically enable or disable a field based on the selection of a radio button? Here are the rules: The field should only be active when the "Inactive" radio button is selected Check out the code snippet below for reference: Radio B ...

Geometry is making its debut appearance in ThreeJS for the very first time!

Currently, I am experimenting with a simple script using ThreeJS to create a point wherever you click on the screen. Below is the function responsible for adding the point: function addPoint(coord){ var geometry = new THREE.BufferGeometry(); var verti ...

Connection to external sources has been deactivated

I am experiencing an issue on my website at . When attempting to click on a link, it seems to be disabled. I suspect this is due to the presence of two images at the end of the navigation bar. Removing these images causes the navigation bar to fall apart, ...

My Discord bot powered by Discord.js is being unresponsive to commands

Hello, I'm facing a major issue with my command handler that I've been struggling with for a while now. The problem is that my bot doesn't respond when I try to use a command. I've tried various methods from YouTube but none of them see ...

The request from localhost:3000 to localhost:3003 could not be proxied by ReactJS

Currently, I am working on developing a Single Page Application (SPA) using create-react-app with an expressjs server as the backend. During development, my frontend test server runs on port 3000 while my backend expressjs test server runs on port 3003. T ...

Create personalized styles for each item within a stack with specific spacing using the @mui library

Is there a way to change both the background color and spacing area when hovering over each item in my list? https://i.stack.imgur.com/87TST.png <Stack spacing={4} divider={<Divider variant={`fullWidth`} orientation={`horizontal`} flexItem/>}> ...

Error encountered in node.js script due to misuse of Sqlite's SQLITE_MISUSE functionality

Upon running my code with this query, I have encountered a situation where all tables are listed sometimes, while other times only one table is shown and consistently the following error is displayed: Query Error: Error: SQLITE_MISUSE: unknown error I ha ...

Utilize passed props in components as well as Redux state information

Typically, you can access props sent by a parent to a child component on the child component itself. However, when using Redux in child components, the props sent by the parent are lost due to the use of the 'connect' method which maps the Redux ...

Discover a corresponding object within an array

I am currently dealing with an array of objects in Javascript where I need to verify if a certain value exists within any object and return the corresponding id. The issue arises when using the some() function as it only seems to match the first object. T ...

What is the best way to update the src of an input using an onclick event?

When I click the input, my background changes color as expected. However, the src of the input only changes on the second click. How can I make it change the source on the first click? Also, how can I change the src back to the original with a second cli ...

Implementing hover effect triggered by keyboard input

Is there a way to create a hover effect on a div when a specific key is pressed on the keyboard using jQuery? <div id="d-up" class="button"></div> Appreciate any help with this! Thank you. ...

Step-by-step guide to initializing a project using React with Typescript and a functional server-side script

I am working on a project that involves a React Typescript app (created using Create React App). In this project, I need to have an executable script that can run alongside the React app. Both the app and the script are intended to only run on local machin ...

Ways to showcase an icon within a select options tag

Is there a way to show Font Awesome icons in select options tag? I have tried using it outside like this <i class="fas fa-chart-pie"></i> But I'm not sure how to display it within the <option> tags instead of text. <select id="s ...