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

Using a custom filter in AngularJS allows for seamless data filtering directly from the initial dataset

My goal is to implement a custom filter that will allow me to filter data based on a search word. The scope attribute gets populated in the controller's scope as shown below: naApp.controller('naCareNewTicketCtrl', ['$scope', &apo ...

How can I make the outer function in AJAX's onreadystatechange function return 'true'?

Within my Javascript/AJAX function below, I am striving for a return of true or false: function submitValidate() { var xmlhttp; xmlhttp = null; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari try { xmlhttp ...

Send form information using the REST method

Can someone provide guidance on how to properly handle this endpoint in my code? @PostMapping("/createUser") public ResponseEntity<User> createUser(@RequestBody User user) {...} I am looking to implement a user creation feature on my HTML ...

jquery animation does not reset after event occurs

My script is functioning well to animate my elements, but I am facing an issue where when the function is called again after a timer, the elements move to their correct positions but do not initiate a new animation. The goal of the function updateFlights( ...

Using jsPlumb to Access an Element After a "Mouseup" Event has Completed

$(document).on('mouseup', '.agent-wrapper', function(info){ console.log(info); // Everything is working fine console.log(this); }); .agent-wrapper represents an element-wrapper for all jsPlumb objects. $(document).on(' ...

ng-repeat displaying an empty list

Currently, I am working on an AngularJS application where I am attempting to display data retrieved using the http get method from a RESTServer. The GET request is sent from one view and upon success, it navigates to another view within AngularJS. Both vi ...

Challenge implementing custom javascript to display categorical/string features on Shiny slider

I'm attempting to design a unique Shiny slider that represents the months of the year. My desired outcome is for the slider to display the names of the months as strings, rather than numeric values where 1 corresponds to January, 2 corresponds to Febr ...

Sliding elements horizontally with jQuery from right to left

I recently purchased a WordPress theme and I'm looking to customize the JavaScript behavior when the page loads. Currently, my titles animate from top to bottom but I want to change this behavior dynamically. You can view it in action here: I have ...

Converting the structure of an object into an array structure for highcharts can be achieved through

I am looking to transform the object structure below: [ { "tahun": "2010", "apel": 100, "pisang": 200, "anggur": 300, "nanas": 400, "melon": 500 }, { ...

How come the method $.when().pipe().then() is functioning properly while $.when().then().then() is not working as expected

I'm still grappling with the concept of using JQuery's Deferred objects, and am faced with a puzzling issue. In this code snippet, my attempt to chain deferred.then() was unsuccessful as all three functions executed simultaneously. It wasn't ...

Troubleshooting: React.js State not updating properly on forms

New to React and facing a challenge with changing the state of form inputs. Here's what I'm trying to do: constructor(props) { super(props); this.state = { pwd:'', email:'', value:'' ...

Issue with Node.js OAuth authentication

As someone new to Node.js and specifically OAuth, I have been exploring the use of Google APIs with Node.js. So far, here is what I've accomplished: var fs = require('fs'); var readline = require('readline'); var google = require( ...

issue with node callback function - code malfunctioning

I have written a script in Node.js and Express to send an email after a SQL transaction is successfully completed! router.post('/',function(req,res,next){ sql.connect(config).then(function() { var request = new sql.Request(); ...

Cover the entire screen with numerous DIV elements

Situation: I am currently tackling a web design project that involves filling the entire screen with 60px x 60px DIVs. These DIVs act as tiles on a virtual wall, each changing color randomly when hovered over. Issue: The challenge arises when the monitor ...

Managing messaging broadcasts for messenger bots by creating and retrieving unique identifiers

As a beginner using a starter project from glitch, I have a project set up at this link: I need help understanding how to obtain the message_broadcast_id and how to create it. This is how I usually create a normal message: function callSendAPI(messageDa ...

In what way can you reach an unfamiliar form within a controller?

I am working with multiple dynamically generated forms, each associated with a different model. In my controller, I need to iterate through all the errors within the forms. I assign form names based on the models. <form name="{{myForm}}" novalidate> ...

Customize the appearance of the Vue.js datepicker starting from today's date

I am currently using the vue-datepicker component to display a date input field in my form. I want to set the default date to the current day and disable the selection of past dates. Additionally, I need to change the language of the component but it seems ...

Implementing concurrent operations in React Native using Firebase, combining async/await with Promise.all

import fire from '../config/fire'; const db = fire.firestore(); class InitialDb extends Component { constructor(props) { super(props); this.state = { schools: '', students: '', }; } async compo ...

magnetic container: stationary container nested within absolutely positioned container

I recently created a page that can be viewed here: [LINK] This page is set up to scroll horizontally, resulting in a row of divs with black borders. However, I am facing an issue with the smaller divs inside (red ones). I want them to stay within the par ...

Exploring various templates with AngularJS Directives

Let's delve into a slightly complex topic, but I'll simplify it as much as possible for you. There is a directive in play: .directive('configuratorRows', function () { return { restrict: 'A', scope: { ...