使用Javascript的系统时钟计时器

时间:2013-04-23 03:31:07

标签: javascript animation timer

我正在尝试使用系统时钟在Javascript中制作一个简单的动画。我想遍历一个数组,以[0],[1],[2]...为间隔调用500ms。使用之前Stack Overflow answer中的示例,我正在尝试使用此代码段:

function timer(time,update,complete) {
    var start = new Date().getTime();
    var interval = setInterval(function() {
        var now = (time*1000)-(new Date().getTime()-start);
        if( now <= 0) {
            clearInterval(interval);
            complete();
        }
        else update(Math.floor(now/1000));
    },500); // the smaller this number, the more accurate the timer will be
}

然后使用以下方法调用该函数:

timer(
    5, // seconds
    function(timeleft) { // called every step to update the visible countdown        
        console.log(3 - timeleft );
    },
    function() { // what to do after
        console.log("Timer complete!");
    }
);

这会产生0,1,2,3,"Timer Complete"。但是,我无法弄清楚如何以500毫秒的间隔调用它。我试过调整数字,但我意识到我并不完全理解这个函数是如何工作的。是否可以对此进行调整,或者是否存在一些在1s间隔内调用的硬编码浏览器功能?

我尝试将所有值更改为以下内容:

function timer(time,update,complete) {
    var start = new Date().getTime();
    var interval = setInterval(function() {
        var now = (time*500)-(new Date().getTime()-start);
        if( now <= 0) {
            clearInterval(interval);
            complete();
        }
        else update(Math.floor(now/500));
    },500); // the smaller this number, the more accurate the timer will be
}

timer(
    5, // seconds
    function(timeleft) { // called every step to update the visible countdown        
        console.log(5 - timeleft );
    },
    function() { // what to do after
        console.log("Timer complete!");
    }
);

现在产生:

2
3
4
5
Timer complete!

我认为是500毫秒间隔,但我不确定。更改5中的5 - timeleft值也会对其运行的速度产生奇怪的影响。

1 个答案:

答案 0 :(得分:0)

我相信你过于复杂了。如果您想要的是每500毫秒显示一个数组中的每个项目,请使用常规计数器,而不是时间戳和舍入:

function timer(myArray) {
    var counter = 0;
    var interval = setInterval(function() {

        // There are still items we want to display
        if(counter < myArray.length) {
            console.log(myArray[counter]);

        // We have displayed all 
        } else {
            console.log('Finished');
            clearInterval(interval);
        }

        // Increment counter
        counter++;

    }, 500); // 500 here is the interval in msec
}

var arr = ['Item 0', 'Item 1', 'Item 2', 'Item 3'];
timer(arr);

http://jsfiddle.net/AE58p/