7

I got this function that starts a timer on this format 00:00:00 whenever I click on a button. But I don't know how to do functions resume and pause. I've found some snippets that I thought could be helpful but I couldn't make those work. I'm new to using objects in js.

function clock() {
  var pauseObj = new Object();

  var totalSeconds = 0;
  var delay = setInterval(setTime, 1000);

  function setTime() {
    var ctr;
    $(".icon-play").each(function () {
      if ($(this).parent().hasClass('hide')) ctr = ($(this).attr('id')).split('_');
    });

    ++totalSeconds;
    $("#hour_" + ctr[1]).text(pad(Math.floor(totalSeconds / 3600)));
    $("#min_" + ctr[1]).text(pad(Math.floor((totalSeconds / 60) % 60)));
    $("#sec_" + ctr[1]).text(pad(parseInt(totalSeconds % 60)));
  }
}

pad() just adds leading zeros

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
esandrkwn
  • 399
  • 1
  • 6
  • 18

4 Answers4

20

I think it will be better if you will create clock object. See code (see Demo: http://jsfiddle.net/f9X6J/):

var Clock = {
  totalSeconds: 0,

  start: function () {
    var self = this;

    this.interval = setInterval(function () {
      self.totalSeconds += 1;

      $("#hour").text(Math.floor(self.totalSeconds / 3600));
      $("#min").text(Math.floor(self.totalSeconds / 60 % 60));
      $("#sec").text(parseInt(self.totalSeconds % 60));
    }, 1000);
  },

  pause: function () {
    clearInterval(this.interval);
    delete this.interval;
  },

  resume: function () {
    if (!this.interval) this.start();
  }
};

Clock.start();

$('#pauseButton').click(function () { Clock.pause(); });
$('#resumeButton').click(function () { Clock.resume(); });
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
  • Thank you @Speransky. With this approach, how can I call pause or resume onclick of a button? – esandrkwn Sep 19 '12 at 02:12
  • I am not able to undersstand the use of self...this in diff places has different meaning...i am a little confused..can you please explain .I have a diferent approach to this http://jsfiddle.net/wMJuQ/ – HIRA THAKUR Dec 18 '13 at 18:26
  • it works, but it's not precise, because of interval calculation overhead and pausing in the middle of interval. Ideally binding to unixtime should be used, but such timer will be overcomplecated with all these plausing/resuming. – aiven Oct 16 '18 at 21:11
1

Just clearing the interval wouldn't work, because totalSeconds would not get incremented. I would set up a flag that determines if the clock is paused or not.

This flag would be simply set upon calling pause() or unset upon resume(). I separated the totalSeconds increase to a 'tick' timeout that will always be running, even when paused (so that we can keep track of the time when we resume).

The tick function will therefore only update the time if the clock is not paused.

function clock()
{
    var pauseObj = new Object();

    var totalSeconds = 0;
    var isPaused = false;
    var delay = setInterval(tick, 1000);

    function pause()
    {
        isPaused = true;
    }

    function resume()
    {
        isPaused = false;
    }

    function setTime()
    {
        var ctr;
        $(".icon-play").each(function(){
            if( $(this).parent().hasClass('hide') )
                ctr = ($(this).attr('id')).split('_');
        });

        $("#hour_" + ctr[1]).text(pad(Math.floor(totalSeconds/3600)));
        $("#min_" + ctr[1]).text(pad( Math.floor((totalSeconds/60)%60)));
        $("#sec_" + ctr[1]).text(pad(parseInt(totalSeconds%60)));
    }

    function tick()
    {
        ++totalSeconds;

        if (!isPaused)
           setTime();
    }
}
dcasadevall
  • 316
  • 1
  • 5
0

Use window.clearInterval to cancel repeated action which was set up using setInterval().

clearInterval(delay);
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • How would you restart it since setTime() is inside function clock()? – HeatfanJohn Sep 19 '12 at 01:31
  • @HeatfanJohn It depends on the meaning of `pause`, if you just want pause the display and let the timer continue, then don't use `clearInterval`, you just need to stop refresh the display of the html content. – xdazz Sep 19 '12 at 01:44
0
    <html>
    <head><title>Timer</title>
    <script>

    //Evaluate the expression at the specified interval using setInterval()
    var a = setInterval(function(){disp()},1000);

    //Write the display() for timer
    function disp()
    {
         var x = new Date(); 

         //locale is used to return the Date object as string
         x= x.toLocaleTimeString();

        //Get the element by ID in disp()
        document.getElementById("x").innerHTML=x;
    }
    function stop()
    {
         //clearInterval() is used to pause the timer
        clearInterval(a);
    }
    function start()
    {    
        //setInterval() is used to resume the timer
        a=setInterval(function(){disp()},1000);
    }

    </script>
    </head>
    <body>
    <p id = "x"></p>
    <button onclick = "stop()"> Pause </button>
    <button onclick = "start()"> Resume </button>
    </body>
    </html>
VRN
  • 15
  • 1
  • 6