Onichan
Onichan

Reputation: 4516

Stop Timer after Reaching a certain time

Using a javascript timer, I have a Timer that starts at 00:00, and should stop at 00:10 (runs for 10 seconds).

The problem is, how can I continuously check the current value of the timer to stop it after 10 seconds?

    <script>
        window.onload = function() {
            var timer = new Tock({
                callback: function () {
                    $('#clockface').val(timer.msToTime(timer.lap()));
                }
            });

            timer.start("00:01.780");
        }
    </script>

    <h2>Timer</h2>
    <input id="clockface" placeholder="00:00:00">

Current Attempts:

            setTimeout(timer,1000);

            $('#clockface').change(function(){
               if($('#clockface').val() == "00:05.000") {
                  timer.stop();
                  alert("True");
               } else {
                  alert("False");
               }
            })

Upvotes: 0

Views: 296

Answers (2)

Gabriel Deliu
Gabriel Deliu

Reputation: 66

This seems to work (JSFiddle: http://jsfiddle.net/gabrieldeliu/jLg2wvvL/1/):

var start_time;
var timer = new Tock({
    callback: function() {
        if (start_time && timer.lap() - start_time > 5000) {
            console.log('Stopped at ' + timer.msToTime(timer.lap()));
            timer.stop();
        }
    }
});

timer.start("00:01.780");
start_time = timer.lap();
console.log('Starts at ' + timer.msToTime(start_time));

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172408

Try like this:

var init = new Date().getTime();
var inter = setInterval(function(){
    if(new Date().getTime() - init > 1000)
    {
        clearInterval(inter);
        return;
    }

}, 2500); 

Upvotes: 0

Related Questions