What is the best way to implement a countdown timer in JavaScript?

I need to create a timer based on two specific dates with times provided. However, the current code I have always displays "Left time: 4h 0m 0s" as the output. It's important to note that I must use the given dates and not rely on the current date.

        var endTime = '2023-09-06 19:41:55'; 
        var startTime = '2023-09-06 15:41:55';
        var targetEndTime = new Date(endTime.replace(/-/g, '/'));
        var targetTime = new Date(startTime.replace(/-/g, '/'));

        function updateCountdown() {
            
            if (targetTime < targetEndTime) {
                var timeDiff = targetEndTime - targetTime;
                var hours = Math.floor(timeDiff / (1000 * 60 * 60));
                var minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
                var seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);

                document.getElementById('countdown').innerHTML = 'Remaining time: ' + hours + 'h ' + minutes + 'm ' + seconds + 's';
            } else if (targetEndTime < targetTime) {
                document.getElementById('countdown').innerHTML = 'Task completed.';
            } else {
                document.getElementById('countdown').innerHTML = 'Task expired.';
            }
        }

        setInterval(updateCountdown, 1000); 
        updateCountdown(); 

Answer №1

It is essential to consider the present moment when dealing with time:

var currentTime = new Date().getTime();

var targetDate = new Date('2023-09-06 19:41:55').getTime();

function updateCountdown() {
    var now = new Date().getTime();
    
    if (now < targetDate) {
        var timeDifference = targetDate - now;
        var hours = Math.floor(timeDifference / (1000 * 60 * 60));
        var minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);

        document.getElementById('counting-down').innerHTML = 'Time remaining: ' + hours + 'h ' + minutes + 'm ' + seconds + 's';
    } else if (targetEndTime < targetDate) {
        document.getElementById('counting-down').innerHTML = 'Task completed.';
    } else {
        document.getElementById('counting-down').innerHTML = 'Deadline passed.';
    }
}

setInterval(updateCountdown, 1000);
updateCountdown();
<div id="counting-down"></div>

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

Comparing npm start and running the app with node app.js

I'm brand new to exploring the world of Node and understanding the basics of app development. I find it interesting how these two commands seem to have a similar output: node app.js --compared to-- npm start Both commands appear to continue "l ...

Scrollbar magically disappears within a div

I have a div element on my website with the overflow property set to auto, which displays a scrollbar when the content overflows. I'm looking for a way to hide this scrollbar while still allowing users to scroll within the div. Any assistance would be ...

Tips for removing a class with ng-class when a value is empty or evaluates to nothing

I'm facing an issue with a class I've created called .lines-hover. My goal is to remove this class when the values in the td elements are empty. For reference, take a look at this example: If you observe closely, on some of the lines, such as M ...

Ember Component Incorporating Keyboard Input

I recently developed an ember component that features a rectangular block in a green canvas. Everything is working smoothly so far. However, I am facing some challenges with implementing keyboard input commands (A S D W) to navigate the rectangle within t ...

What is the best way to reassess the quantity of a specific element once a for loop has finished executing?

const removeBtnCustom = document.querySelectorAll('.customRemove'); for(let i=0; i<removeBtnCustom.length; i++){ removeBtnCustom[i].addEventListener('click', ()=>{ const itemToDelete = document.querySelectorAll('. ...

Refreshing a node in Jqgrid Treegrid by updating the local source data

I have constructed a Treegrid using local data $("#historyGrid").jqGrid({ datatype: "jsonstring", datastr : treeGridObject , colNames:["Id","Channel","Current","History","Delta"], colModel:[ {name:'id', index:'Id&apo ...

Tips for inserting the final array into the designated div

While working on creating a navigation menu with dropdown and multi-menu functions, I encountered some issues that needed to be addressed. After making several improvements, there is still one area that confuses me. Perhaps I can find the solution here. ...

Are there any significant changes in Angular when transitioning from Angular 8 to 9 with regards to the nativeElement?

After upgrading my angular cli version to 9.1.4 from the previous version 8, I am wondering if there are any breaking changes related to nativeElement functionality. Below is a snippet of code from my TypeScript file where I have used nativeElement: impo ...

Attempt to retrieve JSON-formatted data from a repository on Git

As a novice, I am delving into the world of ajax and experimenting with json files. Utilizing JSON formatted data is something I am keen on mastering. However, my request seems to be yielding an empty outcome. An Update: Below is the piece of code I am wor ...

Use JavaScript to identify and color the intersecting area of two triangles that overlap on a webpage

I created two triangular divs using HTML and I am utilizing jQuery UI to enable them to be draggable. Now, my goal is to overlap these two triangles and change the color of the overlapping area to a different shade. Here is an example: https://i.sstatic. ...

Unable to capture the text within the span element. Attempting to retrieve a response from a previously run javascript function

Currently, I am facing a challenging task in FileMaker using Webdirect. I have implemented a QR code generator and reader, and while I can successfully read the code, I am struggling to capture the result of the scan. The scanned data is displayed in a hid ...

Despite updating the database, AJAX is still not showing successful results

After trying multiple methods, I am facing an issue where the PHP script successfully updates the table but the changes are not being reflected in the JavaScript code. Here is what I have been attempting: $sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISO ...

Cordova encountered an error: Execution of inline script was denied due to violation of Content Security Policy directive

As I delve into the world of Cordova and jquery mobile, I encountered a perplexing error that reads: Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' data: gap: 'un ...

Issue with ng-click not functioning in Internet Explorer when selecting an option in AngularJS

I have the following HTML code snippet HTML: <select style="width: 100%" name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple> <option ng-click="BRPTab.AddFilesToOpenorDelete(fileName)" ng-repeat="fileName in BRP ...

Tips for navigating through an array of images

I am attempting to create a feature similar to Snapchat stories, where an array of images is displayed for a set amount of time before returning to the previous screen. Here is an example code snippet: if (images.length > 0) { let timeout; ...

Stop HTML5 video playback when resizing the window

I am currently working on a responsive HTML banner that includes a video using the video tag. The entire unit scales with the window size, and I have set up a breakpoint to trigger new divs when the window width is below 820px. This is achieved with the fo ...

Creating balanced numerical values within the range of 0 to 1 using an array

Is there a way to create a set of numbers between 0 and 1 that is proportional to an array of sales with varying sizes? For instance, if the sales values are [1, 80, 2000], would it be possible to generate an array like [0.1, 0.4, 1]? ...

VueJS Unit Testing: Exploring the Content of Attributes- What to Test?

I'm currently facing some challenges with my initial VueJS unit tests using Jest. Although I grasp the concept and have already executed my first set of successful tests, I find myself pondering over the question of "What aspects should I test?" For ...

Embedding Facebook data into an HTML document

While I am able to retrieve data from Facebook and display it on the console, I am facing issues when trying to display it on an HTML page. I attempted using: $("#mydiv").text(data); or $("#mydiv").append(data); However, this displays [object Object] ...

What is the best way to use jQuery to increment the number in an input field by a specific value?

My goal is to utilize jQuery to increment a number in an input field and then display the updated value in the same input field. The specific id of this input field is "total". Here's my attempt so far: function addBag(){ var bagprice = 79.99; ...