3

I'm writing a jQuery plugin for fast-counting up to a value when a page loads. Since javascript can't run as fast as I want it to for larger numbers, I want to increase the increment step so that it completes within a given timeframe, so I'd need a quadratic function that passes through origo and has it's turning point at y = target counting value and x = target duration, but I can't get a grip on the math for doing this. Since both the number and the duration can change, I need to be able to calculate it in javascript aswell.

Hopefully someone can help me with this one!

Mikau
  • 99
  • 6

2 Answers2

3

Let's formalize the statement a bit.

We seek an equation of the form

y = a*x*x + b*x + c

where x is the time axis and y is a count axis. We know that one point on the curve is (0,0) and another point is (xf, yf) where xf is the final time and yf is the target count. Further, you wish for the derivative of this equation to be zero at (xf, yf).

y' = 2*a*x + b

So I have three equations and three unknowns:

(0,0) => 0 = c
(xf, yf) => yf = a*xf*xf + b*xf + c
y' = 0 @ (xf, yf) => 0 = 2*a*xf + b

You should be able to solve it from there.

  • I really like this answer, since it gives me the math to solve the problem. Unfortunately I can only choose one correct answer, and Frederik's answer gave me a lot of help with how to implement it aswell, which I really appreciate since I'm not all that hot with javascript yet. – Mikau Dec 15 '12 at 22:18
2
// Create a quadratic function that passes through origo and has a given extremum.
// x and y are the coordinates for the extremum.
// Returns a function that takes a number and returns a number.
var quadratic = function (x, y) {
    var a = - (y / (x * x));
    var b = (2 * y) / x;
    return function (x) {
        return a * x * x + b * x;
    };
};
Frederik H
  • 1,406
  • 2
  • 13
  • 15