What steps should I take to ensure that this countdown is continuously updating every second?

I created a function that's functioning properly, but I'm looking to update the message every second. Previously, I attempted using

setInterval(countdownTimer(), 1000)
, however, it was unsuccessful. Below is my code snippet!


let x = await msg.channel.send('Calculating...')
async function countdownTimer() {
   const difference = +new Date("2020-06-01") - +new Date();
   let remaining = "Time's up!";

   if (difference > 0) {
       const parts = {
           days: Math.floor(difference / (1000 * 60 * 60 * 24)),
           hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
           minutes: Math.floor((difference / 1000 / 60) % 60),
           seconds: Math.floor((difference / 1000) % 60)
        };

      remaining = Object.keys(parts).map(part => {
          if (!parts[part]) return;
          return `${parts[part]} ${part}`;
      }).join(" ");
     }

    setInterval(() => {
         x.edit(remaining);
     }, 1000);
 }   
 countdownTimer()
 }
 

Answer №1

function initiateCountdown() {
    const timeGap = +new Date("2021-10-15") - +new Date();
    let countdownMessage = "Time's running out!";
    if (timeGap > 0) {
        const components = {
            days: Math.floor(timeGap / (1000 * 60 * 60 * 24)),
            hours: Math.floor((timeGap / (1000 * 60 * 60)) % 24),
            minutes: Math.floor((timeGap / 1000 / 60) % 60),
            seconds: Math.floor((timeGap / 1000) % 60)
        };

        countdownMessage = Object.keys(components)
            .map(component => {
                if (!components[component]) return;
                return `${components[component]} ${component}`;
            })
            .join(" ");
    }
    return countdownMessage;
}
setInterval(() => {
    const countdown = initiateCountdown();
    x.edit(countdown);
}, 1000)

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

Diverse Range of Exports Available in React Component Library

I have been working on developing a component library consisting of multiple independent components. My objective is to enable users to easily import and use these components in their projects, similar to the following: import One from 'component-lib ...

Enhancing w3-import-html with JavaScript

<div id="import" includeHTML="page.html"></div> function getInclude() { var x = document.getElementById("import").includeHTML; //returns 'undefined' alert(x); } function modInclude() { document.getElementById("import") ...

Validating numbers in React JS input fields component

I need assistance with implementing number validation for 3 Textfields in my application. Currently, the code displays an error message if a Textfield is empty, but I am stuck on validating whether the input is text or numbers. import React from 'rea ...

RaphaelJS: Ensuring Consistent Size of SVG Path Shapes

I am currently constructing a website that features an SVG map of the United States using the user-friendly usmap jQuery plugin powered by Raphael. An event is triggered when an individual state on the map is clicked. However, when rendering a single stat ...

Tips for verifying the input field with specific requirements in Angular 6

There is an input field that needs to validate text based on certain logic conditions: No spaces should be allowed in the formula. The operators (and,or) must be lowercase and enclosed in curly brackets {}. The number of opening '(&apos ...

Transferring data from JavaScript to PHP using the $.ajax method for storing information in a MySQL database

I am attempting to make a POST call from a JavaScript file to a PHP file in order to insert a variable into a MySQL database. Here are the basic files I am working with: 1° PHP file for sending the call <html> <head> <script ...

The useRef() hook call in NextJs is deemed invalid

I have been attempting to implement the useRef() hook within a function component in my NextJs project, but I keep encountering the error below. Despite reviewing the React Hook guidelines, I am unable to determine why this error persists and the functio ...

What is the best way to prevent event propagation in d3 with TypeScript?

When working with JavaScript, I often use the following code to prevent event propagation when dragging something. var drag = d3.behavior.drag() .origin(function(d) { return d; }) .on('dragstart', function(e) { d3.event.sourceEvent ...

Utilize the fetch function to showcase information retrieved from a specific endpoint on a webpage using Javascript

Hey there, I have a Node server with an http://localhost:3000/community endpoint. When I make a GET request to this endpoint, it returns information about three different users in the form of JSON objects. [ { "avatar": "http://localhost:3000/avatars ...

showcasing recommended options in the search bar through the use of javaScript

Hey there, I've been working on creating result suggestions for my search bar. The generation process is all set, but I'm facing an issue with displaying the elements on the HTML page. During testing, I keep seeing ${resultItem.name}, and when I ...

Adding a C# variable to a URL in a Razor view using jQuery

My Razor page looks like this: @{ ViewData["Title"] = "mypage"; string ApiAddress = "https://localhost:8114/api/"; } <div> ... </div> @section Scripts{ <script> functio ...

Adding properties with strings as identifiers to classes in TypeScript: A step-by-step guide

I am working with a list of string values that represent the identifiers of fields I need to add to a class. For instance: Consider the following string array: let stringArr = ['player1score', 'player2score', 'player3score' ...

In order to have a Node.js program run synchronously following a for loop

I am struggling with ensuring that the last console statement is executed only after all iterations of the for loop are completed. Currently, this console statement executes immediately once control enters the else statement. Any ideas on how to resolve ...

What makes the ng-file-upload Upload service so special?

Why do I need to use the Upload service with ng-file-upload in this specific way? Upload.upload({ url: '/postMyFormHere', data: { fileToUpload: model.file, someField1: model.field1, someField2: model.field2, ...

retrieve PHP function calls as an array using Ajax

While working in PHP, I have encountered a situation where I needed to call a PHP function using AJAX: <button onclick="loop()">Do It</button> function loop() { $.get("ajax.php", { action: "true" }, function(result) { $("in ...

Click on a button to send the React Router path as a parameter in

I've got a React form with a submission button like this: <Link className="btn btn-secondary btn-width-200 search-submit" to={{pathname: '/booking/search', query: this.state.filters}}> Search </Link> Within the ...

Create a dynamic calendar by integrating dates with Javascript and an HTML table

Recently, I decided to delve into web design again and embark on a challenging project for my father's baseball business. The main task at hand is creating a detailed calendar using HTML tables. After spending a considerable amount of time perfecting ...

The art of perfect alignment: Mastering the positioning of Material-UI Grid

This issue has been resolved Hey there, I'm currently working on a React App with Material-UI and I'm trying to center a Grid item that includes a Card along with two additional Grid items. Below is the relevant code snippet. Although the Cards ...

Is it possible to set the radius of a d3.js circle using a style attribute?

Learn more about styling in d3.js with this detailed guide that explains how style attributes can be leveraged to customize the look of a circle, including fill color, stroke color, and stroke width. Is it possible to adjust the radius of a d3.js circle u ...

Secure your messages with PHP encryption and decrypt them with JavaScript

I am looking for a way to encrypt a message using PHP and then decrypt it using JavaScript on the client side. I tried using Blowfish with mcrypt, but encountered an issue where PHP was outputting non-alphanumeric characters while JavaScript was only displ ...