JavaScript: How can I fix inaccuracy of animation timer?

My test code is here http://jsfiddle.net/jDck9/ Please click run to test it,and please open it using a webkit browser.

Briefly speaking, I want to move a box in given time, simple as this. But my example has issues, maybe is the inaccuracy of JS timer, my example doesn't work well.

It either moved a bit further from target position of stopped animating before arriving onto the target position.

I'm looking for an solution to address this issue, anyone who has any idea?

Answers


  1. There's timestamp param with the step callback, which indicates the time.
  2. As elapsed is float, so it's very difficult to make the newLeft exactlly the same the targetLeft, so just assign targetLeft in the final step.

Here's the new code:

function animate() {

    var start = null, progress;

    function step(timestamp) {

    if (start == null)
        start = timestamp;

    //here we know how many mill-secs passed
    progress = timestamp - start;

    var elapsed = progress / duration;

    if (elapsed >= 1) {

        //well, time is up, just give "left" the right value
        target.style.left = targetLeft + 'px';

    } else {

        var newLeft = existingLeft + (targetLeft - existingLeft) * elapsed;

        //modify the left accordingly
        target.style.left = newLeft + 'px';

        //schedule another animation
        requestAnimationFrame(step);
    }
    }

    //let's go
    requestAnimationFrame(step);
}

http://jsfiddle.net/rooseve/jDck9/8/


You've never assigned newLeft to existingLeft.

This one works:

var target = document.querySelector('.box');
var duration = 1000; // 1 second

var existingLeft = 0;
var targetLeft = 300;

function animate() {
    var step = function () {
        var elapsed = parseFloat(Date.now() - startTime, 10) / duration;
        var newLeft = Math.round(existingLeft + (targetLeft - existingLeft) * elapsed);
        target.style.left = newLeft + 'px';
        existingLeft = newLeft;

        if(elapsed >=1) {
            // stop
        } else {
            requestAnimationFrame(step);
        }
    }
    step();
}

var startTime = Date.now();
animate();

Need Your Help

Visual Studio Test project base directory

c# directory testing base

I want to do some interaction testing in my test project, and would like to test some xml configuration based components... How can I find the base directory of the test project in code so that I can