The Math.floor function is producing a result of NaN

While this code works fine in Chrome, I am encountering issues with IE and Firefox as it returns NaN. Any insights or assistance would be greatly appreciated.

Essentially, this code is intended to be a simple countdown function for days. If there are errors in my implementation, please feel free to point them out.

var start_date = "09 Sep 16";

var end = new Date(start_date); // set expiry date and time..

var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24
var timer;

function showRemaining()
{
    var now = new Date();
    var distance = end - now;
    if (distance < 0 ) {
       // handle expiry here..
       clearInterval( timer ); // stop the timer from continuing ..
       alert('Expired'); // alert a message that the timer has expired..

       return; // break out of the function so that we do not update the counters with negative values..
    }
    var days = Math.floor(distance / _day);
    document.getElementById('date').innerHTML = ' ' + days + ' ';

}
timer = setInterval(showRemaining, 1000);
Count down: <div id="date"></div>

Answer №1

Looking at my output in the console:

> new Date("09 Sep 16")
< [date] Invalid Date

If you perform any mathematical operations with an invalid date, the result will be NaN.

To avoid this issue, it's recommended to either use the ISO-8601 date format when specifying the date (e.g., new Date("2016-09-09")) or opt for the non-string-parsing version (new Date(2016,8,9))

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

Preventing Vue.js from triggering watch on initial load

I need to implement a feature where a button is initially disabled and only becomes enabled when the input value is changed. To achieve this, I am using a boolean flag that is set to true by default and turns false only when the input changes. The v-model ...

What is the method for configuring the URL of an ajax request to open in a separate window?

I am currently working on an ajax call where I need to open a URL in a new tab or window. Since I'm still learning about ajax, I would greatly appreciate any help and explanation that you can provide. Below is the code snippet: $.ajax({ url: &apo ...

AppProps in Next.js - Ensure that you have the correct loader set up to handle this specific file type as there are currently no loaders configured for processing it

I've encountered an issue while working on a Next.JS 13.5.6 application in development mode. When I try to connect to the site, I receive an error message. However, everything works fine when I switch to production mode after building and starting the ...

Tips for extracting innerHTML or sub-string from all elements that have a specific class name using JavaScript

When it comes to shortening the innerHTML of an element by its Id, I have found success using either slice or substring. While I'm not entirely clear on the differences between the two methods, both accomplish what I need them to do. The code snippet ...

Stop dishonesty in a timed internet assessment

At my company, we frequently host online competitions that involve simple multiple-choice quizzes. The winner is determined by the fastest completion time. Lately, we have been facing a major issue with cheaters submitting quiz entries in less than one se ...

In a React application, the input field unexpectedly loses focus after typing just one character

Has anyone encountered an issue with a dropdown menu causing input field focus to be lost after typing one character? I've attempted setting unique keys for each field, but it hasn't resolved the problem. For reference, here is the link to the p ...

Symfony: The Database Query Button with a Pop-up Feature

I am looking to create a button that will automatically search my database for all users with a "secouriste" attribute set and display their first name, last name, and phone number in a popup. After conducting research, here is what I have gathered: In m ...

Transform MVC4 model into a JavaScript JSON object within a cshtml file

I have a model on my cshtml page that I need to convert into a JSON object for use in the JavaScript on the same cshtml page. I am using MVC4. What is the best way to achieve this? ...

Unsuccessful attempt at aborting an Ajax request

Currently, I have developed a basic live search feature using jQuery ajax to search through a JSON file on the server and display a list of events. The script is programmed to show a list of events that were previously displayed on the page if the search ...

Conceal the menu when tapping anywhere else

I am working on a project that involves implementing HTML menus that can be shown or hidden when the user interacts with them. Specifically, I want these menus to hide not only when the user clicks on the header again but also when they click outside of th ...

Challenges with receiving form submissions

I'm new to asking questions here, but I've been reading articles and questions for a while now. My question is about a specific part of a code that has been causing me trouble. In my project, I have a registration form with both JS validation an ...

The NodeJS program fails to authenticate the Google Calendar API integration, resulting in an undefined response even when valid credentials and tokens are provided

I am seeking assistance with my Google Calendar API integration in NodeJS. I am encountering an error message indicating that the daily limit for unauthenticated use has been exceeded, requiring signup for continued usage. Despite researching this issue on ...

Creating a backup link for a video player component in NextJs

My aim is to make sure that two video player components in a NextJS application can still access and play videos even when the application is running locally using npm run dev without an internet connection. Currently, these two components.. <HoverVi ...

Functionality not functioning within Shadow DOM

After creating and exporting an Angular Element as a single script tag (user-poll.js), using the element on a host site is simple. Just include the following two lines: <user-poll></user-poll> <script src="path/to/user-poll.js"></sc ...

Master the art of positioning in three.js framework

I am a beginner in javascript and three.js, and I am currently exploring how to determine the 3d positions on a webpage. For instance, I want to place a point light at the coordinates (50,20,10) in x, y, z values. How can I determine where these x, y, z va ...

Copying the label for data to a jQuery array can be done by selecting the desired label

Allow me to clarify I am attempting to create a jQuery array containing values copied from a form field. Below is a snippet of the HTML code. <p class="form"> <input id="Dataweekend0" class="radiob" name="form[Dataweekend]" ...

"Implementing a show/hide feature for a DIV based on a selected drop-down value using vanilla JavaScript (without any external libraries

I have different tide tables for various locations, each contained within its own div. The user can select a location from a dropdown menu, and when the page loads, it displays the tide table for the first location by default. Upon changing the location, o ...

Guide to attaching a mouse click event listener to a child element within a Polymer custom component

I'm currently facing an issue where I am attempting to attach a click listener to one of the buttons within a custom element during the "created" life cycle callback (even attempted using the "ready" callback with the same outcome). Unfortunately, I ...

The Google Maps geocoding service fails to provide accurate location information

I am currently attempting to utilize the Google Maps Geocoding API within my JavaScript code. Below is the snippet I have written: var geocoder = new google.maps.Geocoder(); function geocodeAddress() { var address = document.getElementById("address").v ...

ReactJs - SyntaxError: The JSX content is not properly terminated

I'm just starting out with ReactJs and have come across an issue that I can't seem to figure out. Here's my code snippet: var ListComponent = React.createClass({ render: function() { return ( <li>{this.props.va ...