Using animation.width() in Javascript to create a countdown

Currently, I am working on creating a visual countdown for my users to indicate when an animation will finish. The code snippet below shows my initial attempt:

function setClassAndFire(){
    timer = setInterval(function () {
            t--;
            $(this).attr('class', 'timerAnimation');
            countdownTimer();
            if (t === 0) {
                clearInterval(timer);
                timer = undefined;
                funcForCall();
            }
    }, 1000);  
}

function countdownTimer(){
    var timerCurrentWidth = $('.timerAnimation').width(),
        timerMaxWidth = $("#awardQueueText").width(),
        pxPerSecond = timerMaxWidth / 60,
        currentCountdown = timerCurrentWidth / pxPerSecond;
        currentCountdown = Math.round(currentCountdown);
        document.getElementById("timer").innerHTML = "<span style='white-space : nowrap;'>Animation ends in:</br></span>"+
            "<span style='white-space : nowrap;'>" + currentCountdown + " sec.</span>";
}

It's important to note that the animation countdown only represents the time before we can send an API call. If there is something in the queue, the animation will restart.

The current implementation works but has some hiccups:

Sometimes, the countdown skips subtracting a second and compensates by subtracting 2 seconds in the next iteration.

This issue may be due to using Math.round() on currentCountdown. Is there a workaround for this problem? Since I have the maximum width of the animation object, could I separate it from the current width?

How can I make it work seamlessly? It's crucial to align the timer with the animation for the desired functionality. When the animation count reaches 25, I want the displayed number to also show 25!

Answer №1

This issue arose due to the number retrieved from the width, which cannot contain decimals (or is often truncated). In order to resolve this problem, it would be advisable to assign a separate variable for displaying the number and for storing the width of the DOM element. It seems that the variable t is what needs to be utilized in this case; hence, giving it a try would likely address the concern.

 function setClassAndFire(){
        timer = setInterval(function () {
                t--; //What does 't' represent? 
                $(this).attr('class', 'timerAnimation');
                countdownTimer(t);
                if (t === 0) {
                    clearInterval(timer);
                    timer = undefined;
                    funcForCall();
                }
        }, 1000);  
    }

function countdownTimer(t){
        document.getElementById("timer").innerHTML = "<span style='white-space : nowrap;'>Animation ends in:</br></span>"+
            "<span style='white-space : nowrap;'>" + t+ " sec.</span>";
}

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

Is there a way to prevent Material-UI SpeedDial from automatically closing when a SpeedDialAction button is clicked?

Looking to customize the functionality of Material-UI's SpeedDial component (https://material-ui.com/api/speed-dial/). At present, when a SpeedDialAction is clicked, the main SpeedDial component automatically closes. I want to modify this behavior s ...

Using setState in an external function: A step-by-step guide

import Request from 'superagent'; const fetchApi = () => { let apiUrl = '/* URL */'; return Request.get(apiUrl).then((response) => { this.setState({ data: response.body }); }); } export d ...

Are the results displayed in a vertical array format?

Being new to this world, I would greatly appreciate any assistance! I am working with Bootstrap checkboxes and trying to print them using jQuery's window.print function. However, the issue I am facing is that the array I create from the checkboxes d ...

Show users who liked a post from 2 different collections in Meteor

How do I retrieve a list of users who have "liked" this post from a collection and display it in a template? Collections: likes: { "_id": 1234, "userId": "1dsaf8sd2", "postId": "123445" }, { "_id": 1235, "userId": "23f4g4e4", "pos ...

RxJS Observables trigger the onCompleted function after completing a series of asynchronous actions

I have been attempting to design an observable that generates values from various asynchronous actions, particularly HTTP requests from a Jenkins server, which will notify a subscriber once all the actions are finished. However, it seems like there might b ...

The like count displayed in Django's AJAX feature is identical for every post

Having an issue with the ajax setup in my django twitter clone app. Every post's like count remains the same after clicking the like button, but it gets updated after a page refresh. I'm close to fixing it, but currently stuck. View: def add_li ...

Troubleshooting Media Queries Problems in HTML and CSS

Check out the code snippet below: //Modifying text content (function() { var texts = $(".altered"); var textIndex = -1; function displayNextText() { ++textIndex; var t = texts.eq(textIndex) .fadeIn(2000) if (textIndex < te ...

Using HTML and JavaScript to create a link that appears as a URL but actually directs to a JavaScript function

I am working on an HTML page and I am trying to create a link that appears to go to 'example.html' but actually goes to 'javascript:ajaxLoad(example.html);'. Here is what I have tried: <a href="example" onclick="javascipt:ajaxLoad( ...

Stop accidental clicking on objects in React-Fiber which are using Three.js

Check out this interactive cube made up of planes! An issue I've encountered is that clicking on a plane passes through to the ones behind it, rather than only registering a click on the plane directly under my mouse. Any suggestions for fixing this ...

"An issue with the colyseus server has been detected within the JavaScript code

I have written some code but it seems to be causing errors. const colyseus = require("colyseus"); const http = require("http"); const express = require("express"); const port = process.env.port || 3000; const app = express(); ...

Placing one text above another text

I recently came across a unique font that requires both fill and shadow to be used together, with the fill on top and the shadow underneath. I managed to layer them successfully using relative and absolute positioning, as shown in this example. Here is ho ...

Combining JWT authentication with access control lists: a comprehensive guide

I have successfully integrated passport with a JWT strategy, and it is functioning well. My jwt-protected routes are structured like this... app.get('/thingThatRequiresLogin/:id', passport.authenticate('jwt', { session: false }), thing ...

After deploying on Vercel, Next.js' getServerSideProps function is returning undefined

I am trying to create a Netflix-inspired website using next.js. I am able to fetch movie data from TMDB using getServerSideProps(). While everything works as expected in development mode, once deployed on Vercel (re-deployed multiple times), the props I re ...

Manage the size of the menu element within Material-UI

I'm currently working on incorporating a menu item with a login form inside it. The functionality is there, but the width of the form is way too small. I've been searching through the documentation for a solution, but haven't come across any ...

Loading custom places in ArcGIS from a file or database

Hey there, I was wondering about loading custom places with Arcgis similar to Google maps loading from a .xml file. I noticed that Arcgis uses examples saved in .json format, but when I tried putting the example .json on my local server it wouldn't lo ...

Displaying content using asynchronous JavaScript and XML (AJAX

I'm currently working on implementing an infinite scroll feature, where more content is loaded as the user reaches the bottom of the page. I am making an ajax call and attempting to render a new view on the backend before sending it back to the fronte ...

Encircling the most recently selected image with a border

I have successfully made some <img> elements act like <input type="radio"> buttons and now I want to visually indicate the user's selection by adding a border around the chosen image. My challenge is that there are multiple rows of images ...

Encountering issues with installing packages while creating a new Angular 9 project

Recently I updated to node version 12.16.1 (LTS) and Angular CLI version 9.0.3. After creating a new project with the CLI, all files in the root folder are generated but it gets stuck during the installation of node packages. Has anyone else encountered t ...

Adjust the Container's gutters in MaterialUI according to screen sizes

I am trying to adjust the gutters for different screen sizes in my project. I want to turn off the gutters for xs, sm, and md, but have them enabled at xl and larger. Despite following the API documentation, it doesn't seem to be working as expected. ...

Move content off the screen using CSS3 translation

Throughout various projects, I have encountered the need to make elements on a webpage translate out of view (essentially making them fly out of the document). The idea was that by simply adding a class to the element, the CSS would take care of the animat ...