JavaScript: How can I fix inaccuracy of animation timer?

My test code is here 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?


  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 = targetLeft + 'px';

    } else {

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

        //modify the left accordingly = newLeft + 'px';

        //schedule another animation

    //let's go

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( - startTime, 10) / duration;
        var newLeft = Math.round(existingLeft + (targetLeft - existingLeft) * elapsed); = newLeft + 'px';
        existingLeft = newLeft;

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

var startTime =;

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