Jeff
Jeff

Reputation: 1800

Starting, stopping & refreshing timer javascript

I have a little fiddle here where I'm starting/stopping/resetting a javascript timer.

The functionality needs to be a timer runs on a page. When the timer is up, it sends a message, then restarts. The stop button will stop the timer completely.

The fiddle above has the functionality I just described, however I feel like I'm not doing this correctly. Is setTimeout the correct way to create this timer? Should I use setInterval instead?

Secondly, my reset code looks like :

var onReset = function() {
        clearTimeout(timerHandle);
        onStart();    
};

Is there a more elegant way to reset a timer in javascript?

Thanks.

Upvotes: 1

Views: 772

Answers (1)

Ally
Ally

Reputation: 4942

The only improvement I can offer is for you to put it all in an encapsulated object, ask if you want an example. Or if you want to keep the structure you've got then change your onStart function to this to remove a bit of un-needed code.

var onStart = function() {

    timerHandle = setInterval(function() {
        $("#console").append("timer fired.. <br />");
    }, 2000);

};

Fiddle here http://jsfiddle.net/qx6CM/

Upvotes: 1

Related Questions