Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8082349
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T17:03:58+00:00 2026-06-05T17:03:58+00:00

First of all I want to mention two things, One: My code isn’t perfect

  • 0

First of all I want to mention two things,
One: My code isn’t perfect (esspechially the eval parts) – but I wanted to try something for my self, and see if I could duplicate the jQuery Animation function, so please forgive my “bad” practices, and please don’t suggest that I’ll use jQuery, I wanted to experiment.
Two: This code isn’t done yet, and I just wanted to figure out what makes it work badly.

So the animation runs for about 12 seconds while the duration parameter I entered was 15 seconds, What am I doing wrong?

function animate(elem, attr, duration){
  if(attr.constructor === Object){//check for object literal
    var i = 0;
    var cssProp = [];
    var cssValue = [];
    for(key in attr) {
          cssProp[i] =  key;
          cssValue[i] = attr[key];
    }
    var fps = (1000 / 60);
    var t = setInterval(function(){
      for(var j=0;j<cssProp.length;j++){
        if(document.getElementById(elem).style[cssProp[j]].length == 0){
          //asign basic value in css if the object dosn't have one.
         document.getElementById(elem).style[cssProp[j]]= 0;
        }
        var c = document.getElementById(elem).style[cssProp[j]];
        //console.log(str +" | "+c+"|"+cssValue[j]);
        if(c > cssValue[j]){
            document.getElementById(elem).style[cssProp[j]] -= 1/((duration/fps)*(c-cssValue[j]));
        }else if(c < cssValue[j]){
            document.getElementById(elem).style[cssProp[j]] += 1/((duration/fps)*(c-cssValue[j]));
        }else if(c == cssValue[j]){
            window.clearInterval(t);
        }
      }
    },fps);
  }
}
  animate('hello',{opacity:0},15000);

html:

  <p id="hello" style="opacity:1;">Hello World</p>

Note: I guess there is a problem with the

(duration/fps)*(c-cssValue[j])

Part or/and the interval of the setInterval (fps variable).

Thanks in advance.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T17:04:01+00:00Added an answer on June 5, 2026 at 5:04 pm

    I’m not gonna try and refactor that and figure it out, cause it’s pretty wonky. That said… a few things.

    Don’t rely on the value you are animating to let you know animation progress

    In general your approach is unsound. You are better off keeping track of progress yourself. Also, as a result of your approach your math seems like it’s trying too hard, and should be much simpler.

    Think of it like this: your animation is complete when the time has elapsed, not when the animated value seems to indicate that it’s at the final position.

    Don’t increment, set

    Floating point math is inexact, and repeated addition cumulation like this is going accumulate floating point errors as well. And it’s far more readable to make some variables to keep track of progress for you, which you can use in calculations.

    animatedValue += changeOnThisFrame // BAD!
    animatedValue = valueOnThisFrame   // GOOD!
    

    Don’t do the positive/negative conditional dance

    It turns out that 10 + 10 and 10 - (-10) is really the same thing. Which means you can always add the values, but the rate of change can be negative or positive, and the value will animate in the appropriate direction.

    timeouts and intervals aren’t exact

    Turns out setTimeout(fn, 50) actually means to schedule the fn to be call at least 50ms later. The next JS run loop to execute after those 50ms will run the function, so you can’t rely on it to be perfectly accurate.

    That said it’s usually within a few milliseconds. But 60fps is about 16ms for frame, and that timer may actually fire in a variable amount of time from 16-22ms. So when you do calculations based on frame rate, it’s not matching the actual time elapsed closely at all.

    Refactor complex math

    Deconstructing this line here is gonna be hard.

    document.getElementById(elem).style[cssProp[j]] -= 1/((duration/fps)*(c-cssValue[j]));
    

    Why for more complex break it up so you can easily understand what’s going on here. refactoring this line alone, I might do this:

    var style = document.getElementById(elem).style;
    var changeThisFrame = duration/fps;
    var someOddCalculatedValue = c-cssValue[j];
    style[cssProp[j]] -= 1 / (changeThisFrame * someOddCalculatedValue);
    

    Doing this makes it clearer what each expression in your math means and what it’s for. And because you didn’t do it here, I had a very hard time wondering why c-cssValue[j] was in there and what it represents.

    Simple Example

    This is less capable than what you have, but it shows the approach you should be taking. It uses the animation start time to create the perfect value, depending on how complete the animation should be, where it started, and where it’s going. It doesn’t use the current animated value to determine anything, and is guaranteed to run the full length of the animation.

    var anim = function(elem, duration) {
    
        // save when we started for calculating progress
        var startedAt = Date.now();
    
        // set animation bounds
        var startValue = 10;
        var endValue   = 200;
    
        // figure out how much change we have over the whole animation
        var delta = endValue - startValue;
    
        // Animation function, to run at 60 fps.
        var t = setInterval(function(){
    
            // How far are we into the animation, on a scale of 0 to 1.
            var progress = (Date.now() - startedAt) / duration;
    
            // If we passed 1, the animation is over so clean up.
            if (progress > 1) {
                alert('DONE! Elapsed: ' + (Date.now() - startedAt) + 'ms');
                clearInterval(t);
            }
    
            // Set the real value.
            elem.style.top = startValue + (progress * delta) + "px";
    
        }, 1000 / 60);
    };
    
    anim(document.getElementById('foo'), 5000);
    ​
    

    JSFiddle: http://jsfiddle.net/DSRst/

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

First of all, I want to say sorry for this very big question, but
First of all I want to apologize for my bad English. I have a
First of all i want to say that i have searched each and every
First of all i want to say that I'm still a beginner in ASP.NET
First of all, I want to make something clear before I get yelled at:
First of all, i want to apologize for my poor English for it is
First of all, I don't want to use a join because that will make
First of all, I want to be clear that I'm not talking about defining
First of all I don't know if this is the right approach. I want
I want to implement program by c# application. first of all I need web

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.