-2

How would I make a stopwatch in Javascript/jQuery?

I have developed a few methods of my own, here is one using while loops. This stopwatch is merely meant to count for a minute.

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

myStopwatch()
gilbert-v
  • 1,263
  • 1
  • 11
  • 23

3 Answers3

1

Using setInterval() may be better idea:

var count=0;
var timer = setInterval(function(){
    if(count<60) count++;
    else clearInterval(timer);
},3000);
Michał
  • 2,456
  • 4
  • 26
  • 33
0

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);
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • should't this be a comment instead of answer? – isJustMe Mar 31 '14 at 20:25
  • @isJustMe - Finished adding to it now. – jfriend00 Mar 31 '14 at 20:27
  • yea it looks a lot better now – isJustMe Mar 31 '14 at 20:27
  • But why not just use setInterval()? In other words, what are the advatages to setTimeout()? – gilbert-v Mar 31 '14 at 20:31
  • @user3412847 - it entirely depends upon what you're trying to do and how you want to structure the code. `setTimeout()` is obviously what you use if just want it to fire once in the future and obviously the purpose of `setInterval()` is to make a repeating callback. If I want a repeating callback, sometimes I use `setInterval()` and sometimes I want more control over the timing of future intervals so I use repeated `setTimeout()` calls. It all depends upon the particular code and what it's trying to do. – jfriend00 Mar 31 '14 at 20:38
  • @jfriend00 Ok, thank you for your help, I should have been less vague. – gilbert-v Mar 31 '14 at 20:40
0

Use setInterval...

var count = 0;

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

var timer = setInterval(doEverySecond, 1000)
Billy Moon
  • 57,113
  • 24
  • 136
  • 237