What is the best way to create a timer using JavaScript?

I'm looking for a reverse timer to track session timeout. I found a code on codepen that works as a clockwise timer, but my attempts to make it counterclockwise have failed. Can someone please suggest a solution? I want the timeout to be either 1 hour or 59 minutes and 59 seconds. Please assist me. Check out the Codepen demo here.

if((intervalCounter%1000)==0){
                currentTime += 1000;
                var appendHour = currentTime / (1000 * 60 * 60) | 0; 
                var appendMinute = currentTime % (1000 * 60 * 60) / (1000 * 60) | 0;
                var appendSecond = currentTime  % (1000 * 60) / 1000 | 0;

                appendHour = appendHour < 10 ? "0" + appendHour : appendHour;
                appendMinute = appendMinute < 10 ? "0" + appendMinute : appendMinute;
                appendSecond = appendSecond < 10 ? "0" + appendSecond : appendSecond;
                hour.html(appendHour);
                min.html(appendMinute);
                sec.html(appendSecond);

                }

Answer №1

This particular code snippet is designed to operate in the anti-clockwise direction. The example provided below should give you a better understanding of how it functions.

// Set the date we're counting down to
var countDownDate = new Date("July 5, 2019 15:37:25").getTime();

// Update the countdown every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();
    
  // Calculate the difference between now and the specified countdown date
  var distance = countDownDate - now;
    
  // Perform time calculations for days, hours, minutes, and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
  // Display the results within an element with the id "demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";
    
  // If the countdown has concluded, display a message
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="demo"></p>

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

What steps do I need to take to create an animation where an outline gradually becomes filled in

I've been experimenting with creating a loading animation inspired by the pre-loading animation on this website. My attempt using chat GPT resulted in an unexpected outcome where, instead of filling the SVG, it placed a black square on top of it. The ...

What steps can I take to ensure the proper formatting of the `select` input on Mac OS?

How can I maintain consistent formatting for my form across different operating systems? Currently, the form looks good on Windows, but I want to ensure that the select input appears consistently on Mac OS, iOS, and Android devices as well. The image bel ...

How can you deactivate the vue-router for specific routes? Is it possible to operate a single-page application backend while utilizing a non-single-page

I'm currently working on a website/webapp using Laravel 5.3 and Vue 2. Since SEO is crucial, I've decided to keep the frontend/crawlable part of the site in Laravel + Blade, with only minimal sections in Vue 2.0. This way, I can avoid using Ajax ...

Understanding the error handling in Express.js

Learning about error handling in express is new to me and I have a straightforward piece of code like this - const express = require('express'); const MongoClient = require('mongodb').MongoClient; const app = express(); let url = &a ...

Angular Controller is not able to retrieve the Route Parameter, resulting in a 404

Currently working on my very first web app using Node.js and AngularJs. I've encountered a roadblock with the following code: var app = angular.module('Martin', ['ngResource','ngRoute']); app.config(['$routeProvide ...

Utilizing the principles of object orientation in Javascript to enhance event management

After attempting to modularize my JavaScript and make it object oriented, I found myself struggling when dealing with components that have multiple instances. This is an example of how my code currently looks: The HTML file structure is as follows: & ...

Has Jade stopped allowing inline variables unless enclosed by JavaScript markers?

Back when I was using Jade version 0.34.1 (prior to the release of version 1.0.0), I had the ability to incorporate inline variables like this: test = 'fun' p #{test} This would typically result in: <p>fun</p> However, the output ...

Creating Custom Styles with Polymer for <content> Elements

Seeking help with styling using the ::content selector and custom CSS properties. Any insight would be appreciated! To simplify, I have a Polymer component utilizing a content tag that will always contain a paper-input: <template> <style> ...

Exporting SVG to image in Ionic is successful on Android devices, but the image gets cut off when viewed on

I am facing an issue with exporting an SVG as a base64 encoded image and sending it to the server for storage on Google Cloud Storage. The process works fine on Android and in browsers, but fails when attempted on a physical device running IOS. On IOS, t ...

Troubleshooting unexpected issues with dynamically updating HTML using innerHTML

Need help with a renderWorkoutUpdated function that replaces specific workout records with updated values. _renderWorkoutUpdated(currentWorkout) { let html = `<li class="workout workout--${currentWorkout.type}" data-id="${ curre ...

Is there an issue with the JSON data?

"stocksdata" :[{"id":7,"SCRIP":"ASIANPAINT","LTP":3341,"OHL":"BUY","ORB15":"BREAKOUT","ORB30":"NT","PRB":"NA","CAMARILLA& ...

Resizing images in different web browsers: Chrome, IE, and Safari

I'm currently in the process of building a website that utilizes the jquery tabs api. Each tab on the site contains an image that I would like to resize dynamically as the browser window size changes. Here is an example of one of the tabs: <li st ...

Adapting a CSS design

Having some trouble with creating a CSS style. Here's what I have so far: http://jsfiddle.net/WhNRK/26/ Originally designed for a label, but now attempting to modify it for something like this: <input type='radio' name='mcq' ...

AngularJS RESTful Routing Masterclass

I am in the process of organizing my application using the Restful/Ruby convention /<resource>/[method]/[id]. In the past, when working with a server-side MVC framework like CodeIgniter, I would dynamically route based on the URI: For example: www. ...

Strange CSS Problem: Button dysfunction in displays sized 13 inches or 15 inches

I have made a landing page using the latest version of bootstrap. However, I am encountering an odd issue where the success button is not clickable on certain devices such as 13-inch and 15-inch laptops and desktops. You can find the URL for the landing p ...

Remove Vue Component from the styling of current application

We integrated a Vue component (using Vuetify) into our existing .NET MVC application. The issue we are facing is that the Vue component is inheriting all the CSS styles from the rest of the application. Here's a simplified version of the HTML structur ...

How can the value be accessed when using getElementById in Angular for <mat-select> elements that do not have a value attribute?

Within a loop, I have an element that has a dynamically generated id: <mat-select multiple class="dw-input" [value]="element.txn_type_id ? element.txn_type_id.split(',') : []" id="field-{{element.Name}}-txn_type_id&quo ...

What are some ways to monitor the movement of elements and activate functions at precise locations?

I am working on a project that involves a #ball element which, when clicked, utilizes jQuery animate to move downwards by 210px. The code I currently have is as follows: $('#ball').click(function() { $(this).animate({ top: '+=2 ...

Retrieve the latest entry from a JSON file containing epoch timestamps

Currently, I am in the process of developing an app using angularjs. In my json data, I have timestamps and corresponding values like below: { "dps": { "1455719820": 0, "1455720150": 0, "1455720480": 0, "1455720810": 0, " ...

What is the method to store and retrieve data attributes linked to elements such as select options within the React framework?

Despite my efforts, I'm currently unable to retrieve the data attribute from an option using React as it keeps returning null. <select onChange={(e) => this.onIndustryChangeOption(e)} value={this.props.selectedIndustry}> <opti ...