Start a timer in CodeIgniter when a button is clicked and show the time elapsed

Just a heads up: I am currently in the learning process. While I have some experience with PHP, my knowledge of Java is very limited or non-existent. In the past, I've received negative feedback due to this lack of experience. So, here I am giving it another shot.

My goal is to initiate a timer for 24 hours when a button is clicked and display this timer. Once the 24-hour mark is reached, it should update tables in the database. The challenge lies in the fact that this button is nested within an if statement, which complicates matters.

Upon clicking this button, the 24-hour timer should start displaying time in HH:MM:SS format. I've experimented with a few timer scripts, but I'm uncertain about how to integrate them. Here's the timer script that I came across:

<script>
function Timer(duration, display) 
{
    var timer = duration, hours, minutes, seconds;
    setInterval(function () {
        hours = parseInt((timer /3600)%24, 10)
        minutes = parseInt((timer / 60)%60, 10)
        seconds = parseInt(timer % 60, 10);

        hours = hours < 10 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(hours +":"+minutes + ":" + seconds);

        --timer;
    }, 1000);
}

jQuery(function start($) 
{
    var twentyFourHours = 24 * 60 * 60;
    var display = $('#remainingTime');
    Timer(twentyFourHours, display);
});


 
</script>

Here is the corresponding statement:

<?php if($provinces['nation_name'] == "") {
     '<center><button onclick="start()">Start Nation</button></center>';
          } 
?>

I believe that my issue lies in getting it to recognize the function within the IF statement. At this point, my focus is solely on making this functionality work before moving on to the post-timer update task.

Answer №1

After reviewing the question, I attempted to recreate the scenario you described. I made some modifications to the original code to demonstrate how the task can be accomplished. Once you are satisfied with the solution, remember to make any necessary adjustments.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    </head>

    <body>
        <span id="remainingTime">Timer</span>

        <?PHP
            // Modify the following if condition based on your requirements.
            if(true) {
                echo("<button onclick='start()'>Start Timer</button>");
            }
        ?>

        <script>
            function Timer(duration, display) {
                let timer = duration, hours, minutes, seconds;

                let setIntervalId = setInterval(function () {
                    hours = parseInt((timer / 3600) % 24, 10)
                    minutes = parseInt((timer / 60) % 60, 10)
                    seconds = parseInt(timer % 60, 10);

                    hours = hours < 10 ? "0" + hours : hours;
                    minutes = minutes < 10 ? "0" + minutes : minutes;
                    seconds = seconds < 10 ? "0" + seconds : seconds;

                    display.text(hours + ":" + minutes + ":" + seconds);

                    --timer;
                    if (timer === -1) {
                        clearInterval(setIntervalId);
                        // Implement the required action here, such as triggering an event to update the database.
                    }
                }, 1000);
            }

            function start() {
                // Set a test value of 10 seconds for demo purposes.
                let twentyFourHours = 24 * 60 * 60;
                const display = $('#remainingTime');
                Timer(twentyFourHours, display);
            }
        </script>
    </body>
</html>

I've isolated this code into a standalone file so that it can run independently without any other dependencies, aiding in clarity and ease of testing.

You can evaluate the functionality by copying and pasting the provided code here.

Two key modifications have been applied:

  1. The button is now placed within the echo statement inside PHP tags.

  2. Utilized clearInterval to prevent the timer from continuing after reaching zero. Feel free to experiment with removing clearInterval to observe the impact.

Hopefully, these updates meet your needs effectively.

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

Acquire the current audio video stream directly from the web browser

Currently, I am utilizing a JavaScript library that internally invokes getUserMedia. My objective is to access the stream object that has already been initiated. Unfortunately, the library does not provide any means to retrieve it. Is there a method avai ...

Attempting to extract a text string from a chunk of HTML code

My goal is to extract a text string (specifically, an article title) from a snippet of HTML code. The title in question reads "Journalist Allegedly Spied on Zoom Meetings of Rivals in Hilariously Dumb Ways." The challenge lies in the fact that the title d ...

I am encountering an error with an Unhandled Promise Rejection, but I am unable to determine the reason behind it

const express = require('express'); const cors = require('cors'); const massive = require('massive'); const bodyParser = require('body-parser'); const config = require('../config'); const app = express(); ...

Differences between ClosureFeedbackCellArray and FeedbackVector in the V8 engine

Can you explain the distinction between ClosureFeedbackCellArray and FeedbackVector within V8? What steps are necessary to initiate the shift from ClosureFeedbackCellArray to FeedbackVector? What is the significance of the InterruptBudget attribute found ...

Bypass the typical practice of choosing input with javascript

I have a form with a select input that has a dropdown list of options. The requirement is that when the select input is clicked, I need to validate the form. If the form is incomplete, I want to prevent the select input from showing the option list. Howeve ...

Reducing file size through compression (gzip) on express js version 4.4.1

My express js app is functioning as a web server, but I am having trouble with serving unzipped static content (js and css files). I have tried using compression from https://github.com/expressjs/compression, but it doesn't seem to be working for me. ...

Can the performance of a system be impacted by node.js cron?

I am looking to incorporate a cron module (such as later or node-cron) into my node server for job scheduling. The jobs in question involve sending notifications (e.g., email) to remind users to update their profile picture if they haven't done so wit ...

Using ajax to call the Google Maps Api is proving to be ineffective

I am facing some issues with a website. On this particular webpage (), I am trying to display a Google map on the location page using an AJAX function. The getLocation.php file is being called by AJAX: <?php echo '<div id="map-canvas"></ ...

Prevent elements from displaying until Masonry has been properly set up

My goal is to merge Masonry elements with existing ones. Currently, the items appear before Masonry initializes then quickly adjust into position a moment later. I want them to remain hidden until they are in their proper place. This is the snippet (with ...

Ensuring secure deletion of a list entity in CodeIgniter

I am currently developing a to-do list application using CodeIgniter. To retrieve all the lists created by the currently logged in user, I use the following code snippet: <?php $this->db->from('lists'); $current_user = ...

The HTML slideshow is not automatically showing up as intended

I need to make a few adjustments to the picture slideshow on my website. Currently, all the pictures are displayed at once when you first visit the site, and it only turns into a slideshow when you click the scroll arrows. I want it to start as a slideshow ...

The execution of the return statement in the catch block is unsuccessful

Here is a simple example that results in an error because the variable tl was not specified: function allmatches() { SpreadsheetApp.getActive().getSheetByName('data').getRange('A1').setValue(tl) } To track any errors that occur durin ...

Tips for successfully retrieving a boolean value from an ASP.Net JavaScript AJAX request using a C# method

Query: Is there a way to call a C# function from JavaScript code on an .aspx webpage to get authentication results based on a username and password? Here is the JavaScript AJAX POST request I am currently using: $.ajax({ type: "POST", ...

Responsive menu not collapsing properly and appearing funky in Drupal

I've managed to create a responsive navigation bar, but I'm encountering two issues. Firstly, when I resize the screen on my test pages, not all of the links hide as expected. Secondly, after inserting the code into Drupal, the nested links appea ...

What is the best way to stop event bubbling in react-router-dom when using the <Link> component?

Hey there! I have a situation that I need help with. I tried putting the Link around the whole post so that I could prevent bubbling for individual buttons, but for some reason stopPropagation() is not working as intended. Following advice from another s ...

Whenever I try to import a directory that contains modules, Webpack encounters an error

I am currently in the process of developing a small npm library to streamline API interaction. Here is an overview of my folder structure... dist/ index.js src/ index.js endpoints/ endpoint1.js package.json webpack.config.js Inside my src/index ...

Error: Unable to locate bundle.js when attempting to refresh the page with a specific ID in the URL

I encountered an issue where I tried redirecting a user to their profile page to display the profile information corresponding to it. Let's say we have http://localhost:8080/user/1 as an example. Upon redirecting the user using the navbar link, the pa ...

Drawing intersecting lines on a javascript canvas and clearing them using the lineto method

I am working with a canvas where lines are drawn based on mouse movement. I am trying to achieve the effect of the line only lasting for a few seconds before disappearing, similar to swirling a ribbon with a set length. I have been using lineTo to draw the ...

Confusion with Javascript callbacks - seeking clarity

I am having difficulty grasping the concept of callback functions. I know that they are functions passed as parameters to other functions. My assumption was that when a function is passed as a parameter, it would be recognized as a callback function and ex ...

How to use jQuery with multiple selectors?

I am attempting to create a feature where multiple links are highlighted when one is clicked. However, I am encountering an issue where only the link that is clicked is being highlighted, rather than all three links. Below is the code snippet: $('#v ...