Attempting to trigger the timer to begin counting down upon accessing the webpage

Take a look at this example I put together in a fiddle:

https://jsfiddle.net/r5yj99bs/1/

I'm aiming to kickstart as soon as the page loads, while still providing the option to pause/resume. Is there a way to show the remaining time as '5 minutes' instead of '300 seconds', and have it count down in that manner rather than just displaying seconds?

<button class="start-pause">Start</button>
<h2 class="time-left"></h2>

var times = [];
var counter_interval;
var $time_left = $('.time-left');
var $button = $('.start-pause');

// timer length in seconds
var timer_length = 300;

$('body').on('click', '.start-pause', function() {

    // are we starting or stopping?
    var starting = times.length % 2 == 0;

    times.push(Date.now());

    if (starting) {
        $button.html('Pause');
        counter_interval = setInterval(function() {


            var time_left = Math.floor(timer_length - sum_elapsed());

            if (time_left < 1) {
                clearInterval(counter_interval);
                return finished();
            }

            $time_left.html(time_left);

        }, 100);
    } else {
        $button.html('Resume');
        clearInterval(counter_interval);
    }
});

var sum_elapsed = function() {
    sum = 0;
    for (var i=0; i<times.length; i++) {
        if (i % 2 == 1) {
            sum += (times[i] - times[i-1]);
        }

        if (i == (times.length - 1)) {
            sum += (Date.now() - times[i]);
        }
    }
    // convert milliseconds to seconds
    return sum / 1000;
};

var finished = function() {
    $button.attr('disabled','disabled').html('Finished');
    $time_left.html("Time's Up");
};

Answer №1

Discover an excellent time management tool known as "moment." This powerful resource can be easily accessed either via npm or moments.com

With the ability to convert relative time into user-friendly, readable formats.

If you prefer a hands-on approach, simply utilize the modulus of seconds by 60 to determine minutes. By applying the modulus function, all essential information regarding hours and beyond can be extracted.

Answer №2

If you want to modify the code below, do the following:

Replace this line:
$time_left.html(time_left);

with:

$time_left.html(secToMinTxt(time_left));

Also, include these two new functions:

function pad(num) {
    var str = "" + num;
    var pad = "00";
    return pad.substring(0, pad.length - str.length) + str;
}

function secToMinTxt(seconds) {
    var min = Math.floor(seconds / 60);
    var sec = seconds % 60;
    return pad(min) + ":" + pad(sec);
}

To see an example of this in action, check out this JSFiddle: https://jsfiddle.net/r5yj99bs/2/

Answer №3

To correctly understand the question, consider utilizing the Math.round function with the current value of the time_left variable divided by 60.

let time_left = Math.round(Math.floor(total_time - elapsed_time()) / 60);

Check out the code on jsfiddle: https://jsfiddle.net/abc123xyz/7/

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

Emailer: Missing Salutation

While attempting to send emails using Node with Nodemailer (https://github.com/nodemailer/nodemailer), the sendMail call from the Nodemailer transporter is throwing an error message of Greeting never received when connected to an Ethereal test email accoun ...

The matter concerning the intricacies of Rails, JQuery, Prototype, and RJS

I am exploring the integration of Jquery and ajax in rails 3.0.7, but I'm unclear on the current landscape regarding their usage together. There seems to be an abundance of hacks, plugins, and scripts available for utilizing JQuery. So: Is there an ...

Eliminate items from one array when there is a corresponding match in a separate array using JavaScript

I am working with 2 JavaScript arrays First Array var columns=[{name: 'id', default: true}, {name: 'type', default: true},{name: 'typeName', default: true}, {name: 'client', default: false}]; Second Array var unSel ...

Building secure applications with React and Express using private routes

In my experience, I have primarily utilized server-side rendering solutions to transfer data from the server to the client and display it in the browser. One of the key advantages of this approach is the ability to access data and send it to the client wi ...

Tips for ensuring proper dependency regulations in javascript/typescript/webpack

In essence, I am in search of a method to limit dependencies, similar to how one would manage different projects (libraries) in Java or C#. Think of it as friend or internal access modifiers. I'm considering various approaches to accomplish this (suc ...

The trick to keeping a div open without it closing until the page is refreshed

I am currently working on a project that involves creating an interactive map with dots. Each dot, when clicked, should trigger the display of a form related to that specific dot within a <div>. My challenge is ensuring that once a dot is clicked an ...

What are the essential Angular 2 observables for me to utilize?

I have created a form input for conducting searches. Upon user input into the search bar, I want to trigger calls to two separate APIs simultaneously. Here is my current attempt: myInput: new FormControl(); listOne: Observable<string[]>; listTwo: Ob ...

What is the best approach in JavaScript to compare and modify properties in two arrays of objects with efficiency?

Here's a method I have written in an Ecma 6 component (Salesforce Lightning Web Components for anyone interested). I am sharing it here because this is more focused on JavaScript rather than LWC. Do you think this is the optimal approach to solve this ...

Is it feasible to create a full-page text gradient clip without it repeating on each individual element?

.gradient { background-color: #00ccaa; background: linear-gradient(0deg, #00ccaa, #f530a9); background-size: cover; background-clip: text; box-decoration-break:slice; -webkit-background-clip: text; -webkit-text-fill-color: transparent; -web ...

Nested routes are arranged in the depths and a variety of components appear depending on the path of the

I've encountered a situation where I have deeply nested routes in my routes.js file. The code snippet below shows that depending on the route, I need to render different components. For instance, if the route is for products, I should render the Produ ...

How can you use CSS to style an image's title attribute?

I am trying to customize the text displayed when hovering over an image. Despite my efforts, the code I used doesn't seem to be working properly: <body> <img src="img.jpg" title="<span class='title'>title</span>" &g ...

Update dataTable with new data fetched through an ajax call from a separate function defined in a different

I need to refresh the data in my datatable after using a function to delete an item. The function for deleting is stored in a separate file from the datatable. Here is the delete function code: function removeFunction(table,id) { var txt= $('.ti ...

Ways to direct to dashboard if a user is logged in using AngularJS

As a newcomer to AngularJS, I am facing an issue with redirecting my page to the dashboard once the user has logged in. I receive an access token after login, which I save in cookies. Despite trying solutions from Stack Overflow, I have not been able to re ...

Utilizing two visuals within the <picture> srcset

Is there a way to include two images on the desktop version (one on the right and one on the left) within the picture tag that replaces the mobile version image? I attempted it but it didn't work as expected. <picture> <source medi ...

What measures can be taken to prevent the reloading of a subfolder within the same parent in the Fuel

var DataSourceTree = function (options) { this.source = options.source; } DataSourceTree.prototype = { data: function (options, callback) { var self = this; var ...

Internal server error frequently occurs when there is an issue with Ajax requests in a Laravel application

Greetings, fellow developers! I am encountering an issue with the comments system in Laravel and Ajax. While it functions correctly with PHP alone, I am facing difficulties when using Ajax. The error message I am receiving is as follows: Status Code:50 ...

NPM packages installed on a global level are not being detected

Recently, I experienced a system crash that led me to delete some files in an attempt to fix the issue. Among those files may have been ~/.profile. Since restoring my system, I've noticed that my globally installed npm packages are no longer functioni ...

A JavaScript regex that can identify white spaces and new lines to calculate word count

Currently, I am attempting to count words within the Summernote editor using Angular. While I have successfully created a service for counting words, it seems to be ineffective when encountering new lines. Here is an example of the text: Hult Internation ...

Halt the execution of a function upon clicking a div element

I'm currently working on a function that needs to be stopped when a div with the class "ego" is clicked. This function toggles the visibility of the header based on the scroll position and should only run by default. Below is the code snippet: $("#e ...

Having trouble with JQuery in JADE?

I recently attempted to create a slideshow for my website, but it appears that my JQuery code is not functioning as expected. Here's the code snippet I used: div#slideshow img(src="/images/img1.png") img(src="/images/ ...