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

The Date.UTC function is not providing the correct output

While attempting to change Unix timestamps into a more understandable format, I used Date.UTC(2017,09,23);. When running this code, it returned 1508716800000. However, upon verifying on the website , the displayed result showed October 23, 2017 instead o ...

Is it possible to apply a style change to several components at once using a single toggle switch

I am looking to implement a day/night feature on my web app, triggered by a simple toggle click. While I can easily add this feature to a single component using the navigation menu, I am faced with the challenge of incorporating it into multiple component ...

Creating a tree-view in Vue.js that includes clickable components which trigger a Vue.js modal to open up

I have a unique requirement to implement a tree-view feature in Vue-JS for displaying JSON data. However, I need to enhance this by triggering a VueJS modal when any of the data fields in the JSON view are clicked. I have explored various npm modules that ...

Unable to locate module: Unable to locate the file './Header.module.scss' in '/vercel/path0/components/Header'

I encountered an error while attempting to deploy my next application on Vercel. I have thoroughly reviewed my imports, but I am unable to pinpoint the issue. Module not found: Can't resolve './Header.module.scss' in '/vercel/path0/comp ...

Is it possible in HTML to detect *any* changes made to an input, not just those made by the keyboard?

Let's consider a scenario where we have an input element like this: <input id="myInput" type="text" /> The question now arises, how can we detect when the value of this input is changed programmatically (such as through $("#myInput").val("new ...

Simple steps to successfully pass two parameters to jsonpCallback

Hey there! Below is the code snippet where I am using an ajax call in jQuery to invoke function 1 named "setEmailAFriendCount". In this function, we are passing a variable with JSON data type. However, I now need to call the same function from an ajax call ...

Date Range Selection Widget malfunctioning when used within a popup modal

Having trouble with integrating the rsuite daterangepicker and antd's daterangepicker into a React Material UI Dialog/Modal. The date picker popup seems to either not show up or appear outside of the modal window. Take a look at the image below: Clic ...

Trouble displaying portrait images in CSS slideshow

My portfolio includes an image slider called wow slider, which can be found at You can view my site with the image slider on this page: http://jackmurdock.site50.net/StudioWork.hmtl While most of the galleries display portrait and landscape images correc ...

Is it possible to update the text within a button when hovering over it in Angular?

I'm looking to update the text displayed inside a button when hovering over it, similar to the examples in these images. I have already implemented the active state, but now I just need to change the text content. <button type="submit" ...

Four unique chip/tag colors, personalized to suit your style

Currently, I have integrated two arrays into my autocomplete menu where the chip/tag color is either primary or secondary based on the array the selected component belongs to. I aim to include all four arrays in the menu (top10Songs, top10Artists, top10Fi ...

Is it possible to use string indexes with jQuery each method in Typescript?

When running a jQuery loop in Typescript, I encountered an issue where the index was being reported as a string. $.each(locations, (index, marker) => { if(this.options && this.options.bounds_marker_limit) { if(index <= (this.opt ...

Using jQuery, you can easily set the value of a datetime picker to "

In my pursuit to implement Php, I came to the conclusion that the functionality needed to be executed on the client side. The "ready" function is successfully functioning. //fechaMin and fechaMax are inputs of type "datetime" $(document).ready(function( ...

Text input fields within a grid do not adjust to different screen sizes when placed within a tab

I noticed that my component under a tab is causing the Textfield to become unresponsive on small screens. To demonstrate this, I checked how the Textfield appears on an iPhone 5/SE screen size. https://i.stack.imgur.com/d8Bql.png Is there a way to make t ...

Error: The options object provided for CSS Loader is not valid and does not match the API schema. Please make sure to provide the correct options when

Summary My Nuxt.js project was created using the command yarn create nuxt-app in SPA mode. However, I encountered an error after installing Storybook where running yarn dev resulted in failure to start the demo page. ERROR Failed to compile with 1 errors ...

Utilizing Typescript in tandem with an external library through es6 modules

Is there a recommended method for incorporating Typescript with non-module libraries like PixiJS and SortableJS without using webpacker? I'm looking to utilize es6 modules but want to avoid cumbersome solutions. What would be the best approach in this ...

Challenges with resizing images in SVG using D3

I have an SVG image created using d3. I am facing an issue where the svg is extending beyond its parent div container. Here is the code snippet: <div id="test" style="{width: 500px; height:500px;}"> <svg></svg> </div> ...

Comparing the special features of jQuery Sortable+Droppable and Draggable functionality

Trying to implement a feature where a draggable list of items (left column) can be dragged onto a sortable list (right column), but with a twist. The sortable list should behave like a droppable list, maintaining the order only when dragging new items and ...

Use JavaScript to sift through an array and exclusively retrieve items that match a specific value

I am working with an array of objects that contain a phase key, and I want to filter out only the ones that have a specific phase value. Additionally, I need to map some other key/value pairs into the final return. Here is my current code: phaseToBlocks ( ...

When setting up columns in a MUI DataGrid, it's important to remember that each field must have a unique name to avoid any conflicts. Having

I am currently working on a DataGrid project where I aim to display the values of ready_by and name. Here is an image for reference: https://i.stack.imgur.com/3qZGa.png In my code configuration, the setup looks like this: (specifically focusing on the la ...

Is It Possible to Determine If a Checkbox Has Been Checked?

Here's what I have now: I have a checkbox that I need to verify if it's selected. <input type="checkbox" name="person_info_check" value="0" &nbps>Read and agree!</input> However, the method I found online to verify the checkbox ...