Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Web Coding › Javascript: Start/Stop/Pause Button for setInterval()
New Posts  All Forums:Forum Nav:

Javascript: Start/Stop/Pause Button for setInterval() - Page 2

post #11 of 17
The way we are doing it now is not the best way to do this. It does not keep proper time. I found an article that explains why http://www.sitepoint.com/creating-accurate-timers-in-javascript/
The author is right, I added a clock to your example page and it quickly went out of sync. So I rewrote my example and it seems to be a lot more accurate.
Code:
<html>
  <head>
  </head>
  <body>
<p id="timer">timer 00:00:00.0</p>

<button id="start" onclick="StartFunction()">Reset/Start</button>
<button id="stop" onclick="StopFunction()">  Stop  </button>
<button id="pause" onclick="PauseFunction()">pause</button>
<script>

/* declare some variables */
  var d = 0;
  var h1 = 0;
  var m1 = 0;
  var s1 = 0;
  var mil1 = 0;

  var h = 0;
  var m = 0;
  var s = 0;
  var mil = 0;
  var timers = 0;

  var start = 0;
  var pause = 0;
  var stoped = 0;

  function timer(){

/* setup the clock and read the time */
      var d = new Date();
      d.setHours((d.getHours()-h1),(d.getMinutes()-m1),(d.getSeconds()-s1),(d.getMilliseconds()-mil1));

/* get the time to work with */
      window.h = d.getHours();
      window.m = d.getMinutes();
      window.s = d.getSeconds();
      window.mil = d.getMilliseconds();

/* add leading zeros (just for looks)*/
      if( h < 10 ) {
        h="0" + h;
      };

      if( m < 10 ) {
        m="0" + m;
      };

      if( s < 10 ) {
        s="0" + s;
      };

/* convert milliseconds to tenths of a second  (just for looks)*/
      window.mili = Math.floor(mil/100);

/* display the timer */
      window.timers = h+":"+m+":"+s+"."+mili;
      document.getElementById("timer").innerHTML = "timer " + timers;

  }


  function StartFunction(){
  
/* start things up */
      window.clearInterval(start);
      window.start=setInterval(timer, 10); 

/* setup the clock, read the time, and set time to 00:00:00 */
      window.d = new Date();
      window.h1=d.getHours();
      window.m1=d.getMinutes();
      window.s1=d.getSeconds();
      window.mil1=d.getMilliseconds();
      window.d.setHours((d.getHours()-h1),(d.getMinutes()-m1),(d.getSeconds()-s1),(d.getMilliseconds()-mil1));
 
/*  */
      window.pause=0;
      window.count=0;
      window.stoped=0;
      document.getElementById("pause").innerHTML="Pause";
      document.getElementById("stop").innerHTML = "Stop";
      document.getElementById("start").innerHTML = "Reset/Start";
      window.ns=1;
  };

  function StopFunction(){

/* stoppes the timer */
      window.clearInterval(start);
      window.stoped=1;
      window.pause=0;

/*  */
      document.getElementById("pause").innerHTML="Pause";
      document.getElementById("stop").innerHTML = "Stopped";
      document.getElementById("start").innerHTML = "Reset/Start";

  }

  function PauseFunction(){

/*  */
      if (ns==0) {
        return;
      };

/*  */
      if (stoped==0) { 
/* pause the timer */
        if (pause==0) {
          window.clearInterval(start);
          document.getElementById("pause").innerHTML="Resume"
          pause=1;
          return;
        };

/* restart the timer where it left off */
        if (pause==1) {
          window.d = new Date();
          window.h1=d.getHours()-h;
          window.m1=d.getMinutes()-m;
          window.s1=d.getSeconds()-s;
          window.mil1=d.getMilliseconds()-mil;
          window.d.setHours((d.getHours()-h1),(d.getMinutes()-m1),(d.getSeconds()-s1),(d.getMilliseconds()-mil1));
          window.start=setInterval(timer, 10); 
          document.getElementById("pause").innerHTML="Pause"
          pause=0;
          return;
        };
      };
    return;
  };

</script>
</body>
</html>
Core I7
(13 items)
 
  
CPUMotherboardGraphicsRAM
I7 920 rev. D0 @ 4.26Ghz EVGA X58 SLI EVGA GTX 285 OCZ XMP 3x2Gb (pc3 12800) 
Hard DriveOptical DriveOSMonitor
Western Digital Caviar Black 640Gb x 2 LG GH22LS30 openSuse 12.1 x64 HP F2105 
PowerCase
CORSAIR 850TX Cooler Master ATCS 840 
  hide details  
Reply
Core I7
(13 items)
 
  
CPUMotherboardGraphicsRAM
I7 920 rev. D0 @ 4.26Ghz EVGA X58 SLI EVGA GTX 285 OCZ XMP 3x2Gb (pc3 12800) 
Hard DriveOptical DriveOSMonitor
Western Digital Caviar Black 640Gb x 2 LG GH22LS30 openSuse 12.1 x64 HP F2105 
PowerCase
CORSAIR 850TX Cooler Master ATCS 840 
  hide details  
Reply
post #12 of 17
Thread Starter 
Hey Tom, thanks for posting the article, I read through it and your example code a few times and have started making appropriate changes.

In the mean time, how does this line of code work?
Code:
d.setHours((d.getHours()-h1),(d.getMinutes()-m1),(d.getSeconds()-s1),(d.getMilliseconds()-mil1));

I couldn't find anything about it in W3Schools, so how does it work better than say...
Code:
d.setHours(d.getHours()-h1);
d.setMinutes(d.getMinutes()-m1);
etc.
Dynamix
(15 items)
 
  
CPUMotherboardGraphicsRAM
i7-860 Gigabyte GA-P55A-UD4P Radeon 7970 Corsair Domintor Twins + Other = 16 Gb 
Hard DriveHard DriveOptical DriveCooling
WD Caviar Black, 500gb OCZ Solid 3 Sony Optiarc Corsair H50 
OSMonitorKeyboardPower
Windows 7 Ultimate Samsung P2570HD + Other Logitech G110 Corsair 750W HX 
CaseMouse
Antec p183 Logitech MX Revolution 
  hide details  
Reply
Dynamix
(15 items)
 
  
CPUMotherboardGraphicsRAM
i7-860 Gigabyte GA-P55A-UD4P Radeon 7970 Corsair Domintor Twins + Other = 16 Gb 
Hard DriveHard DriveOptical DriveCooling
WD Caviar Black, 500gb OCZ Solid 3 Sony Optiarc Corsair H50 
OSMonitorKeyboardPower
Windows 7 Ultimate Samsung P2570HD + Other Logitech G110 Corsair 750W HX 
CaseMouse
Antec p183 Logitech MX Revolution 
  hide details  
Reply
post #13 of 17
Quote:
Originally Posted by Zen00 View Post

Hey Tom, thanks for posting the article, I read through it and your example code a few times and have started making appropriate changes.

In the mean time, how does this line of code work?
Code:
d.setHours((d.getHours()-h1),(d.getMinutes()-m1),(d.getSeconds()-s1),(d.getMilliseconds()-mil1));

I couldn't find anything about it in W3Schools, so how does it work better than say...
Code:
d.setHours(d.getHours()-h1);
d.setMinutes(d.getMinutes()-m1);
etc.
It's the same just all in one command
Code:
Date.setHours(hour,min,sec,millisec)
Core I7
(13 items)
 
  
CPUMotherboardGraphicsRAM
I7 920 rev. D0 @ 4.26Ghz EVGA X58 SLI EVGA GTX 285 OCZ XMP 3x2Gb (pc3 12800) 
Hard DriveOptical DriveOSMonitor
Western Digital Caviar Black 640Gb x 2 LG GH22LS30 openSuse 12.1 x64 HP F2105 
PowerCase
CORSAIR 850TX Cooler Master ATCS 840 
  hide details  
Reply
Core I7
(13 items)
 
  
CPUMotherboardGraphicsRAM
I7 920 rev. D0 @ 4.26Ghz EVGA X58 SLI EVGA GTX 285 OCZ XMP 3x2Gb (pc3 12800) 
Hard DriveOptical DriveOSMonitor
Western Digital Caviar Black 640Gb x 2 LG GH22LS30 openSuse 12.1 x64 HP F2105 
PowerCase
CORSAIR 850TX Cooler Master ATCS 840 
  hide details  
Reply
post #14 of 17
Thread Starter 
Thanks for the help, here's the new code. By the way, why do you use "window." in front of everything? Can't find a good explanation and would like one if it would help me write better.

Anyways, this should be the final version now. You can also see it in action on zenproductions.co.nf
Code:
<!DOCTYPE HTML>
<html lang="en">
        <head>
                <style type="text/css">
                        body {
                                background-color:black;
                                background-image:url('sites/default/files/simpletimerimages/timerappbackground.png');
                                background-position:center top;
                                background-repeat:no-repeat;
                                width:700px;
                                height:900px;
                                margin:0 auto 0 auto;
                        }
                        
                        #gobutton {
                                position:relative;
                                left:240px;
                                top:244px;
                        }
                        
                        #stopbutton {
                                position:relative;
                                left:16px;
                                top:465px;
                        }
                        
                        #display {
                                position:relative;
                                width:250px;
                                left:226px;
                                top:185px;
                                color: gold;
                                font-size: 50px;
                                font-family: Verdana, Geneva, Tahoma, sans-serif;
                                text-align:center;
                        }
                </style>
        
                <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
                <title>Simple Timer</title>
                <meta name="description" content="This webpage demonstrates the capabilities of the Simple Timer for people who do not have access to a webOS operating device.">
        </head>
        
        <body>
                <div id="display">
                        <label id="hours">00</label>:<label id="minutes">00</label>:<label id="seconds">00</label>
                </div>
                <input type="image" id="gobutton" src="sites/default/files/simpletimerimages/gobutton.png" alt="Go Button" width="220" height="220" onclick="startTimer()">
                <input type="image" id="stopbutton" src="sites/default/files/simpletimerimages/stopbutton.png" alt="Stop Button" width="220" height="220" onclick="stopTimer()">

                <script type="text/javascript">
                        <!--
                        /* variable setup */
                        var hoursLabel = document.getElementById("hours");
                        var minutesLabel = document.getElementById("minutes");
                        var secondsLabel = document.getElementById("seconds");
                        var test = document.getElementById("test");
                        var totalMills = 0;
                        var totalSeconds = 0;
                        var totalMinutes = 0;
                        var totalHours = 0;
                        var startHours = 0;
                        var startMinutes = 0;
                        var startSeconds = 0;
                        var startMills = 0;
                        var counter = 0;
                        var timerOn = 0;
                        var htmlResets = 0;
                        var dateGrab = 0;
                        var timerPaused = 0;
                        var dateStart = 0;
                        var datePaused = 0;
                        
                        /* starts and pauses the timer if conditions are met */
                        function startTimer()
                        {
                                if(timerOn == 1)
                                {
                                        return;
                                }
                                else if(timerOn == 0 & timerPaused == 0)
                                {
                                        /* setup the initial clock and read the time */
                                        dateStart = new Date();
                                        startHours=dateStart.getHours();
                                        startMinutes=dateStart.getMinutes();
                                        startSeconds=dateStart.getSeconds();
                                        startMills=dateStart.getMilliseconds();
                                        
                                        counter = setInterval(setTime, 10);
                                        timerOn = 1;
                                        htmlResets = 0;
                                }
                                else if(timerOn == 0 & timerPaused == 1)
                                {
                                        /* resets the start date while making time corrections to prevent lose of place */
                                        dateStart = new Date();
                                        startHours = dateStart.getHours() - totalHours;
                                        startMinutes = dateStart.getMinutes() - totalMinutes;
                                        startSeconds = dateStart.getSeconds() - totalSeconds;
                                        startMills = dateStart.getMilliseconds() - totalMills;
                                        dateStart.setHours((dateStart.getHours()-startHours),(dateStart.getMinutes()-startMinutes),(dateStart.getSeconds()-startSeconds),(dateStart.getMilliseconds()-startMills));
                                        counter = setInterval(setTime, 10);
                                        timerOn = 1;
                                        htmlResets = 0;
                                }
                        }
                        
                        /* stops and resets the timer if conditions are met */
                        function stopTimer()
                        {
                                if(timerOn == 1)
                                {
                                        clearInterval(counter);
                                        timerOn = 0;
                                        timerPaused = 1;
                                }
                                
                                if(htmlResets == 1)
                                {
                                        hoursLabel.innerHTML = "00";
                                        minutesLabel.innerHTML = "00";
                                        secondsLabel.innerHTML = "00";
                                        totalMills = 0;
                                        totalSeconds = 0;
                                        totalMinutes = 0;
                                        totalHours = 0;
                                        timerPaused = 0;
                                }
                                else
                                {
                                        htmlResets = 1;
                                }
                        }
                        
                        function setTime()
                        {
                                /* setup the new clock , read the time, compare it to the start time, assign variables */
                                dateGrab = new Date();
                                dateGrab.setHours((dateGrab.getHours()-startHours),(dateGrab.getMinutes()-startMinutes),(dateGrab.getSeconds()-startSeconds),(dateGrab.getMilliseconds()-startMills));

                                totalHours = dateGrab.getHours();
                                totalMinutes = dateGrab.getMinutes();
                                totalSeconds = dateGrab.getSeconds();
                                totalMills = dateGrab.getMilliseconds();

                                /* rolls over and resets the timer if left running too long */
                                if(totalHours == 99 & totalMinutes == 59 & totalSeconds == 59)
                                {
                                        totalHours = 0;
                                        totalMinutes = 0;
                                        totalSeconds = 0;
                                        totalMills = 0;
                                        hoursLabel.innerHTML = "00";
                                        minutesLabel.innerHTML = "00";
                                        secondsLabel.innerHTML = "00";
                                        clearInterval(counter);
                                        timerOn = 0;
                                }
                                
                                /* format and display variables */
                                secondsLabel.innerHTML = pad(totalSeconds);
                                minutesLabel.innerHTML = pad(totalMinutes);
                                hoursLabel.innerHTML = pad(totalHours);
                        }
                        
                        /* formats the variables by adding leading "0"s and converting to strings for display */
                        function pad(val)
                        {
                                var valString = val + "";
                                if(valString.length < 2)
                                {
                                        return "0" + valString;
                                }
                                else
                                {
                                        return valString;
                                }
                        }
                //-->
                </script>
        </body>
</html>
Dynamix
(15 items)
 
  
CPUMotherboardGraphicsRAM
i7-860 Gigabyte GA-P55A-UD4P Radeon 7970 Corsair Domintor Twins + Other = 16 Gb 
Hard DriveHard DriveOptical DriveCooling
WD Caviar Black, 500gb OCZ Solid 3 Sony Optiarc Corsair H50 
OSMonitorKeyboardPower
Windows 7 Ultimate Samsung P2570HD + Other Logitech G110 Corsair 750W HX 
CaseMouse
Antec p183 Logitech MX Revolution 
  hide details  
Reply
Dynamix
(15 items)
 
  
CPUMotherboardGraphicsRAM
i7-860 Gigabyte GA-P55A-UD4P Radeon 7970 Corsair Domintor Twins + Other = 16 Gb 
Hard DriveHard DriveOptical DriveCooling
WD Caviar Black, 500gb OCZ Solid 3 Sony Optiarc Corsair H50 
OSMonitorKeyboardPower
Windows 7 Ultimate Samsung P2570HD + Other Logitech G110 Corsair 750W HX 
CaseMouse
Antec p183 Logitech MX Revolution 
  hide details  
Reply
post #15 of 17
How to automatically pause the timer when the mobile browser is in background and resume the timer when we use it without any buttons...for example like a mobile game timer ... i got my code in which my timer starts only when i click any image on the screen. timer is running fine only when it is in use but when its in background and resumed its going below 0 i.e., -1,-2,-3...
Edited by tonychjr - 8/29/13 at 1:01am
post #16 of 17
Quote:
Originally Posted by tom.slick View Post

The way we are doing it now is not the best way to do this. It does not keep proper time. I found an article that explains why http://www.sitepoint.com/creating-accurate-timers-in-javascript/
The author is right, I added a clock to your example page and it quickly went out of sync. So I rewrote my example and it seems to be a lot more accurate.
Code:
<html>
  <head>
  </head>
  <body>
<p id="timer">timer 00:00:00.0</p>

<button id="start" onclick="StartFunction()">Reset/Start</button>
<button id="stop" onclick="StopFunction()">  Stop  </button>
<button id="pause" onclick="PauseFunction()">pause</button>
<script>

/* declare some variables */
  var d = 0;
  var h1 = 0;
  var m1 = 0;
  var s1 = 0;
  var mil1 = 0;

  var h = 0;
  var m = 0;
  var s = 0;
  var mil = 0;
  var timers = 0;

  var start = 0;
  var pause = 0;
  var stoped = 0;

  function timer(){

/* setup the clock and read the time */
      var d = new Date();
      d.setHours((d.getHours()-h1),(d.getMinutes()-m1),(d.getSeconds()-s1),(d.getMilliseconds()-mil1));

/* get the time to work with */
      window.h = d.getHours();
      window.m = d.getMinutes();
      window.s = d.getSeconds();
      window.mil = d.getMilliseconds();

/* add leading zeros (just for looks)*/
      if( h < 10 ) {
        h="0" + h;
      };

      if( m < 10 ) {
        m="0" + m;
      };

      if( s < 10 ) {
        s="0" + s;
      };

/* convert milliseconds to tenths of a second  (just for looks)*/
      window.mili = Math.floor(mil/100);

/* display the timer */
      window.timers = h+":"+m+":"+s+"."+mili;
      document.getElementById("timer").innerHTML = "timer " + timers;

  }


  function StartFunction(){
  
/* start things up */
      window.clearInterval(start);
      window.start=setInterval(timer, 10); 

/* setup the clock, read the time, and set time to 00:00:00 */
      window.d = new Date();
      window.h1=d.getHours();
      window.m1=d.getMinutes();
      window.s1=d.getSeconds();
      window.mil1=d.getMilliseconds();
      window.d.setHours((d.getHours()-h1),(d.getMinutes()-m1),(d.getSeconds()-s1),(d.getMilliseconds()-mil1));
 
/*  */
      window.pause=0;
      window.count=0;
      window.stoped=0;
      document.getElementById("pause").innerHTML="Pause";
      document.getElementById("stop").innerHTML = "Stop";
      document.getElementById("start").innerHTML = "Reset/Start";
      window.ns=1;
  };

  function StopFunction(){

/* stoppes the timer */
      window.clearInterval(start);
      window.stoped=1;
      window.pause=0;

/*  */
      document.getElementById("pause").innerHTML="Pause";
      document.getElementById("stop").innerHTML = "Stopped";
      document.getElementById("start").innerHTML = "Reset/Start";

  }

  function PauseFunction(){

/*  */
      if (ns==0) {
        return;
      };

/*  */
      if (stoped==0) { 
/* pause the timer */
        if (pause==0) {
          window.clearInterval(start);
          document.getElementById("pause").innerHTML="Resume"
          pause=1;
          return;
        };

/* restart the timer where it left off */
        if (pause==1) {
          window.d = new Date();
          window.h1=d.getHours()-h;
          window.m1=d.getMinutes()-m;
          window.s1=d.getSeconds()-s;
          window.mil1=d.getMilliseconds()-mil;
          window.d.setHours((d.getHours()-h1),(d.getMinutes()-m1),(d.getSeconds()-s1),(d.getMilliseconds()-mil1));
          window.start=setInterval(timer, 10); 
          document.getElementById("pause").innerHTML="Pause"
          pause=0;
          return;
        };
      };
    return;
  };

</script>
</body>
</html>


how to use timer without buttons in the above code...like for example if we only open the page then timer starts and pauses when its not in use...
post #17 of 17
Thread Starter 
Dynamix
(15 items)
 
  
CPUMotherboardGraphicsRAM
i7-860 Gigabyte GA-P55A-UD4P Radeon 7970 Corsair Domintor Twins + Other = 16 Gb 
Hard DriveHard DriveOptical DriveCooling
WD Caviar Black, 500gb OCZ Solid 3 Sony Optiarc Corsair H50 
OSMonitorKeyboardPower
Windows 7 Ultimate Samsung P2570HD + Other Logitech G110 Corsair 750W HX 
CaseMouse
Antec p183 Logitech MX Revolution 
  hide details  
Reply
Dynamix
(15 items)
 
  
CPUMotherboardGraphicsRAM
i7-860 Gigabyte GA-P55A-UD4P Radeon 7970 Corsair Domintor Twins + Other = 16 Gb 
Hard DriveHard DriveOptical DriveCooling
WD Caviar Black, 500gb OCZ Solid 3 Sony Optiarc Corsair H50 
OSMonitorKeyboardPower
Windows 7 Ultimate Samsung P2570HD + Other Logitech G110 Corsair 750W HX 
CaseMouse
Antec p183 Logitech MX Revolution 
  hide details  
Reply
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Web Coding
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Web Coding › Javascript: Start/Stop/Pause Button for setInterval()