问题描述:

This question already has an answer here:

  • How to create a stopwatch using JavaScript?

    2 answers

网友答案:

Use setInterval...

var count = 0;

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

var timer = setInterval(doEverySecond, 1000)
网友答案:

Using setInterval() may be better idea:

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

jQuery's .delay() does not halt the execution of javascript like you're trying to do. It only works with asychronous operations that use the jQuery queue system such as animations which means it will do nothing in your current code since you are not using any jQuery queued operations.

In javascript, the way that you "delay" for one second is to use setTimeout() or setInterval() and specify the callback function that you want called at some future time from now.

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

So, if you want to wait for something for a minute, you would do this:

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