我如何在Javascript / jQuery中制作秒表?

时间:2014-03-31 20:21:56

标签: javascript jquery

我如何在Javascript / jQuery中制作秒表?

我开发了一些自己的方法,这里有一个使用while循环。这个秒表仅仅意味着一分钟。

function myStopwatch() {
    var $count = 0;
    while($count < 60) {
        $count++;
    }
$count.delay(1000); //makes $count one second long
}

myStopwatch()

3 个答案:

答案 0 :(得分:1)

使用setInterval()可能更好看:

var count=0;
var timer = setInterval(function(){
    if(count<60) count++;
    else clearInterval(timer);
},3000);

答案 1 :(得分:0)

jQuery的.delay()并没有像你想要的那样停止执行javascript。它只适用于使用jQuery队列系统的异步操作,例如动画,这意味着它不会在当前代码中执行任何操作,因为您没有使用任何jQuery排队操作。

在javascript中,“延迟”一秒钟的方式是使用setTimeout()setInterval()并指定您希望在将来某个时间调用的回调函数。

setTimeout(function() {
     // this code here will execute one second later
}, 1000);
// this code here executes immediately, there is no delay
var x = 1;

所以,如果你想等一会儿,你会这样做:

// execute some code one minute from now
setTimeout(function() {
     // this code here will execute one second later
}, 1000*60);

答案 2 :(得分:0)

使用setInterval ...

var count = 0;

doEverySecond(){
    // something to do every second...
    count++;
    if(count > 60) clearInterval(timer);
}

var timer = setInterval(doEverySecond, 1000)