Cease the countdown once it reaches the specified date

I am currently running a Christmas countdown on my website, but I'm struggling to make it stop once the exact date is reached.

function countdown(){
var now = new Date();
var eventDate = new Date(2016, 11, 25);

var currentTime = now.getTime();
var eventTime = eventDate.getTime();

// remaining time in miliseconds
var remTime = eventTime - currentTime;

// converting into seconds, minutes, hours, days
var s = Math.floor(remTime / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
var d = Math.floor(h / 24);


// finding exact hours, minutes and seconds
h %= 24;
m %= 60;
s %= 60;


d = (d < 10) ? "0" + d : d;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;

document.getElementById("days").innerHTML = d;
document.getElementById("hours").innerHTML = h;
document.getElementById("minutes").innerHTML = m;
document.getElementById("seconds").innerHTML = s;

setInterval(countdown, 1000);
}



countdown();
body {
background: #1f262e;
}

.countdownContainer{
position: absolute; top: 50%; left: 50%;
transform : translateX(-50%) translateY(-50%);
text-align: center;
color: #eff0f2;
padding: 10px;
}

.info {
font-size: 80px;
}

#days, #hours, #minutes, #seconds {
background: #0F1A20;
box-shadow: 0 0 5px 3px #1f262e;
font-size: 120px;
padding: 20px;
}

.title {
font-size: 20px;
}
<table class="countdownContainer" cellspacing="10">

<tr class="title">
<td style="padding-bottom: 20px">DAYS</td>
<td style="padding-bottom: 20px">HOURS</td>
<td style="padding-bottom: 20px">MINUTES</td>
<td style="padding-bottom: 20px">SECONDS</td>
</tr>

<tr class="info" >
<td id="days" border-spacing="10px"></td>
<td id="hours"></td>
<td id="minutes"></td>
<td id="seconds"></td>
</tr>

</table>

I have searched for solutions online, and many suggest using clearInterval, but I am unsure how to implement it in this context.

Thank you

Answer №1

This issue may appear simple, but there are some helpful suggestions to consider:

  1. Consider using setTimeout() over setInterval(). While the former is a one-time event, the latter can lead to intervals accumulating continuously. This could result in browser overload or crashing if not managed properly. Remember to keep track of unique identifiers for each setInterval().

  2. During each call, calculate the values of eventTime and currentTime (both are Unix timestamps in milliseconds). While eventTime remains constant, currentTime will increase by 1000 with each call. Once currentTime surpasses or equals eventTime, it's time to halt the process.

Visit this link for an example.

Answer №2

To stop the countdown, simply use the clearInterval method as shown below:

var countdownTimer = setInterval(countdown, 1000);

function stopCountdown() {
  clearInterval(countdownTimer);
}

Answer №3

Consider utilizing the clearTimeout method.

let timer;
function initiateCountdown() {
 timer = setTimeout('reduceTime()', 1000);
}

clearTimeout(timer);

Answer №4

It is important to ensure that the dates are being compared properly.

If today happens to be the target date, then it would be wise to halt the interval execution.

The interval function will execute your specified function every milliseconds you specify as the second parameter, essentially running it every second.

var myInterval = setInterval(countdown, 1000);

function countdown(){
    var now = new Date();
    var eventDate = new Date(2016, 11, 25);

    var currentTime = now.getTime();
    var eventTime = eventDate.getTime();

    // if today matches Christmas date, stop the interval
    if (currentTime == eventTime) {
      return clearInterval(myInterval);
    }

    // calculate remaining time in milliseconds
    var remTime = eventTime - currentTime;

    // convert into seconds, minutes, hours, days
    var s = Math.floor(remTime / 1000);
    var m = Math.floor(s / 60);
    var h = Math.floor(m / 60);
    var d = Math.floor(h / 24);


    // determine exact hours, minutes and seconds
    h %= 24;
    m %= 60;
    s %= 60;


    d = (d < 10) ? "0" + d : d;
    h = (h < 10) ? "0" + h : h;
    m = (m < 10) ? "0" + m : m;
    s = (s < 10) ? "0" + s : s;

    document.getElementById("days").innerHTML = d;
    document.getElementById("hours").innerHTML = h;
    document.getElementById("minutes").innerHTML = m;
    document.getElementById("seconds").innerHTML = s;

}

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

When executing store.sync() in ExtJS, all fields are passed

In the latest version of ExtJS (6.5.0), I have set up a Store and an editable grid panel: Ext.define('StateStore',{ extend: 'Ext.data.Store', alias: 'store.stateStore', storeId : 'StateStore', field ...

What is the best way to create a reusable component for a Material-UI Snackbar?

Having trouble getting my Alert component to display a message that says "Successfully submitted" in the parent component. The message doesn't seem to be showing up. AlertComponent import React, { useState } from "react"; import { Snackbar, Alert } f ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

Tips for automatically updating the time in a React application while utilizing the 'date-fns' library

I've been working on my personal Portfolio using React and I'm looking to add a feature on the landing page that showcases my local time and timezone to potential recruiters. However, there's a small hiccup in my implementation. The displaye ...

Querying MongoDB to retrieve particular elements from an array within a collection

Results collection contains the following data. _id "9FK5k755ueAYdfip3" createdAt Date {Sat Mar 12 2016 19:58:46 GMT+0100 (CET)} results [Object { errorId="uX6byeiuGjRNXTj6s", error="02/09/15 13:01:29 backu...ox fil ...

Looking to retrieve the key value or iteration of a specific item within an Angular UI tree?

Here is a snippet of code showcasing how to use angular-ui-tree: <div ui-tree> <ol ui-tree-nodes="" ng-model="list"> <li ng-repeat="item in list" ui-tree-node> <div ui-tree-handle> {{item.title}} </div& ...

Is it feasible to utilize the HTML5 video tag in conjunction with a JSON callback?

Curious about the possibility of a video page layout featuring a main screen and smaller clickable screens below it. When clicking on one of the smaller screens, the main screen would display the selected video, similar to YouTube. We have obtained data f ...

Bringing tex2max.js into an angular application using npm and index.html

Every time I attempt to import tex2max with the command declare var tex2max: any;, I encounter a ReferenceError: tex2max is not defined. Interestingly, this issue does not arise with other npm packages. Despite trying various methods such as installing the ...

Importing named exports dynamically in Next.js

Currently, I am in the process of learning Next.js and I want to utilize a function called getItem from the package found at https://www.npmjs.com/package/encrypt-storage In my attempt to do so using the code snippet below, I encountered an error stating ...

Changing the background color of a button

In the HEADER section, there are 4 buttons (B1, B2, B3, B4), each leading to a different page in the same tab. The background color of the buttons is set to WHITE. When a specific button is clicked, the entire page reloads and redirects to the correspond ...

In the event that the user is authenticated within an iframe, proceed to redirect the parent window

Scenario - A situation has arisen where Site X needs to access Site Y through an iframe, both residing on separate servers. Current Progress - X has successfully accessed Y via iframe by adding the following code in the .htaccess file of Y: Header alway ...

using vuejs, learn how to retrieve properties within the .then function

This is the code I am working on: methods: { async pay() { this.$notify(`working`); if (!this.$v.$invalid) { try { var data = { to: this.to, subject: this.subject, }; let resp ...

Issue encountered while constructing NextJS application; error was encountered during the pre-rendering of the

I encountered an issue while trying to deploy my app; specifically, I faced an error during the project building process. info - Loaded env from /Users/furkanulker/Desktop/Projects/dev-project/.env info - Skipping validation of types info - Creating a ...

Ways to personalize the interface following the selection of an item from a dropdown menu

Currently, I am using Vue.js and Typescript for my project work. I have a requirement to customize the interface by making adjustments based on the selected item from a drop-down list. <b-form-select id="input-topic" ...

"Utilize Node to import either all dependencies or selectively choose specific

Should we only require the specific properties we need or the entire object? Example: Below is a snippet from my helper file 'use strict'; /** * getCallback * return a function used to make callback * @param {callback} callback - the callb ...

Is the Okta SDK compatible with all identity providers?

I am looking to incorporate a wide range of Identity providers into my app, such as Auth0 SSO OIDC, Onelogin SSO OIDC, Google SSO OIDC, and others. Is it possible to use this solution to make that happen? https://github.com/okta/okta-auth-js ...

What is the best way to integrate model classes within an Angular module?

I have a few classes that I want to keep as plain bean/DTO classes. They are not meant to be display @component classes, @Pipe classes, or @Directive classes (at least, that's what I believe!). I am trying to bundle them into a module so that they ca ...

Encountering a Component Exception error in React Native while attempting to implement a Victory chart component

Currently, I am exploring the Victory library for react native to create a line chart for my budgeting application. Below is the code snippet from my Graph component: import React from 'react'; import { View, StyleSheet } from 'react-native& ...

How to iterate through two arrays using AngularJS ng-repeat

I have been attempting to create a specific layout by iterating through two arrays However, the output I am receiving from the ng-repeats does not match my desired view Below is the current code that I am working with: $scope.properties = ["First name", ...

I'm encountering difficulty accessing the Index value within the template's Ref

I'm having trouble accessing the index value inside the templateRef. It shows as undefined in the console. <ng-container *ngFor="let notification of notifications; let i = index"> <ng-template *ngTemplateOutlet="notificationPage ...