The Javascript function outputs the time with a negative value

As a newcomer to web development, I am struggling with this code that returns the time in negative. Can someone please provide guidance?

let countDate = new Date('April 1, 2023 00:00:00').getTime();

function countDown() {

    let now = new Date().getTime();
    gap = countDate - now;

    let second = 1000;
    let minute = second * 60;
    let hour = minute * 60;
    let day = hour * 24;

    let d = Math.floor(gap / (day));
    let h = Math.floor((gap % (day)) / (hour));
    let m = Math.floor((gap % (hour)) / (minute));
    let s = Math.floor((gap % (minute)) / (second));

    document.getElementById('day').innerText = d;
    document.getElementById('hour').innerText = h;
    document.getElementById('minute').innerText = m;
    document.getElementById('second').innerText = s;

}

setInterval(function() {
    countDown();
}, 1000)

view image description here

I have attempted to fix the code but I'm still struggling to fully comprehend it. Can someone please explain what needs to be done to correct this issue?

Answer №1

Setting the variable countDate to a specific date and time that occurred in the past.

Answer №2

The getTime() function calculates the number of milliseconds that have passed since the epoch, marked as midnight on January 1, 1970, UTC. (Source: MDN)

As it is now past April 1, 2023 00:00:00, the expression new Date().getTime() will yield a higher value compared to

new Date('April 1, 2023 00:00:00').getTime();
, indicating an increase in milliseconds elapsed.

This leads to a negative result in the calculation countDate - now.

To address this issue, adjust your code to use now - countDate (resulting in a positive value for a past date) or select a future date for your countdown instead.

Answer №3

An issue arises with the line gap = countDate - now;

The date stored in now is actually after the date in countDate, causing it to be calculated as a larger number internally. This can be addressed by reversing the order of the subtraction:

gap = now - countDate;

Answer №4

Your countdate is configured for the past, so it will produce a negative value. I created this codepen to implement validation that once the countdown is complete, it will display day:00, hour:00, minute:00 and second:00, resulting in all zeroes. Feel free to modify the countdate (for example: April 17, 2023) to witness the outcome.

[Access the Codepen here.](https://codepen.io/neyubee/pen/OJBMBYj)

Answer №5

The reason is that your count date is earlier than the current date. You started counting from 1st April 2023, but today is 15th April 2023. Therefore, the date has already passed and you need to make sure your count date is after today's date [i.e count date > 15th April] or you can adjust by changing gap=now-Countdate

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 Execution of a Function Fails When Passed to a Functional Component

My functional component accepts a function called addEvent, which expects an event parameter. The problem arises when I try to call this function from props within another functional component, as the function does not seem to execute: const onOk = () =&g ...

What is the most effective way to extract data that includes an array within it?

const flightList = [{ number: 343, from: "Singapore", to: "India", upgradeTypes: ["Economy to Premium Economy", "Economy to Business Class"] }, . { number: 363, from: "Chennai", to: "Sing ...

How can you use the MongoDB Aggregation Framework to filter by a range of dates, group results by individual days, and calculate the average value for each day

I'm currently exploring the possibilities of MongoDB's Aggregation Framework and would appreciate some assistance in enhancing this query to achieve the following objectives: Retrieve Records with Dates falling within a specified range Organize ...

Clearing the ui-grid after a button is clicked

Is there a method to clear all content from a ui-grid including filters, data, and columns? I want to reset the grid when a button is clicked in order to fetch new data with an HTTP request and display it using the same grid without refreshing the page. ...

React search filter feature with dropdown selection

After successfully implementing a search filter in my React app, I encountered an issue when trying to incorporate a select tag to change the search filter criteria. class BookList extends Component { state = { search: '', selectedValue: ' ...

AJAX is not displaying the expected output

Seeking help on calling a PHP method from JavaScript to query a database and integrate the results into JS functionality. The current 'console.log(output)' in my Ajax returns: "array (size=1) 'action' => string 'getResults&apos ...

Retrieve the sender and count the deleted messages with Discord.js

I currently have a basic message code for pruning, but I am looking to enhance it. const num = args[0] let messages = await message.channel.fetchMessages({ limit: num }); let deletedMessage = await message.channel.bulkDelete(messages, tru ...

Execute the second method once the first method has completed its execution

As I develop my npm package, I am faced with the challenge of ensuring that one method waits for another to complete before executing. For example: var package = require('myNpmPackage'); package.method1(options); ... Later on, possibly in a dif ...

Sorting objects in AngularJS

Within the primary Array Object, my JSON data looks like this obj = [{{"title":"1-Introduction"}, {"title":"5-Introduction"}, {"title":"20-Introduction"}, {"title":"4-Introduction"} }] I am looking to sort the above object as follows ...

Switch background and disable hover effect with a click

I'm facing some issues with JavaScript and I can't seem to solve the problem on my own. What I want is, when I click on #footerblock, for the background of #footerblock to change, and then for the footer to lose its "hover effect". <script> ...

My Javascript code initiates an AJAX request before any other operations are executed

I am facing an issue with my Flask application and client-side JavaScript. I am trying to send an object using AJAX from my JavaScript to the Flask application running on the server side. However, the AJAX request is being sent before the rest of my JavaSc ...

Quick and easy way to access json data with jquery

https://i.sstatic.net/kiEwe.png Need help with reading data from JSON format using jQuery. I've attempted the code below, but I'm having trouble retrieving the exact data I need. $.ajax({ url: '@Url.HttpRouteUrl("GetDistrictLi ...

Encountering a problem sending an array of objects to a controller via jQuery AJAX

I attempted to send an array of objects to a controller using jQuery Ajax, but I am getting a null result in ASP.NET 5.0. The data array that I'm sending is named regions. The constructor for the data is defined in the BoundingBoxModel class. Here i ...

I am having trouble with my jquery.ajax configuration where the async parameter is set to true. The data is not being sent back to

My goal is to save content whenever a button or hyperlink is clicked using jquery.ajax in an Asp.net 3.5 environment. Here is the logic I am following: I use .bind in jquery to attach my custom method(MakeLog) to a button click or hyperlink click. Sinc ...

Retrieve information from the previously selected option in a dropdown menu, along with information from the currently selected option

Dealing with variable scoping in JavaScript can be a bit tricky. I've experimented with various methods like using window.var or declaring variables inside and outside of functions, but nothing seems to work. Here's the scenario: $(".some_field" ...

What are the best practices for managing mouse events in AlpineJS when working with my menu?

I'm currently tackling the challenge of developing a mega dropdown menu feature using alpine.js and Tailwind CSS. Unfortunately, I've hit a roadblock as I can't seem to get the mouse events functioning correctly. In the snippet below, you&ap ...

Styling JSON format in Node.js

I have a code snippet that queries a database and outputs the information in JSON format: connectionpool.getConnection(function(err, connection) { if (err) { console.error('CONNECTION error: ',err); res.statusCode = 503; ...

Dynamic content updates in Vue.js for div elements

As I venture into the world of developing a Single Page Application (SPA) using Vue.js, I find myself facing a steep learning curve due to my limited knowledge on the subject. Despite following a tutorial and managing to get something up and running, I sti ...

Creating interactive buttons on the fly in Angular

In my Angular application, I am attempting to create a button dynamically that calls the deleteRow() function and passes a username parameter upon click. Despite successfully passing the username to the controller, the generated button ends up passing unde ...

My attempts to troubleshoot the JavaScript function have all been unsuccessful

I am completely new to JavaScript and feeling a bit embarrassed that I'm struggling with this. My goal is to build a website that takes first and last names as input and generates email addresses based on that information. Despite my attempts, moving ...