Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Javascript: Start/Stop/Pause without buttons
New Posts  All Forums:Forum Nav:

Javascript: Start/Stop/Pause without buttons

post #1 of 5
Thread Starter 
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...

ref: http://www.overclock.net/t/1354355/javascript-start-stop-pause-button-for-setinterval/10
post #2 of 5
You just need to call those same functions without the buttons. If you're asking what I think you're asking, I've already provided the answer here. In case that wasn't clear enough.

The window object has several events that fire (see them all here). The notable events here are:
window.onunload -- triggers at the same time window closes (don't use this because of IE and AJAX problems)
window.onbeforeunload -- triggers just before the window closes (use this instead of onunload unless support for older versions of Opera is needed)
window.onblur -- triggers when window loses mouse focus
window.onload -- triggers when page finishes loading
window.onfocus -- opposite of onblur. Triggers when window gains mouse focus

.addEventListener('', , false)
.removeEventListener('', , false)


Important note:
NEVER give functions names starting with a capital in javascript. Javascript constructors must begin with the new prefix like:
Code:
var x = new Array();
If you call a constructor without the 'new' keyword, you can clobber the global object (this is very bad). The problem is that constructors look just like regular functions. To avoid this problem, it is universally standard convention to only give constructors upper case first letters.

Code:
<script>
window.addEventListener('beforeunload', stopFunction, false);
window.addEventListener('load', startFunction, false);
window.addEventListener('blur', pauseFunction, false);
window.addEventListener('focus', pauseFunction, false);

</script>

Edited by hajile - 9/1/13 at 4:48pm
post #3 of 5
Thread Starter 
i tried replacing these in the code and there are no errors but the timer is not running...any ideas.
Code:
<button id="start" onclick="StartFunction()">Reset/Start</button>
<button id="stop" onclick="StopFunction()">  Stop  </button>
<button id="pause" onclick="PauseFunction()">pause</button>

\and\

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

post #4 of 5
click to show (Click to show)
Code:
[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) {
          pauseOnBlurFunction()
          //window.clearInterval(start);
          //document.getElementById("pause").innerHTML="Resume"
          //pause=1;
          return;
        };

/* restart the timer where it left off */
        if (pause==1) {
          unPauseOnFocusFunction()
          //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;
  };
  
  function pauseOnBlurFunction(){

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

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

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

/*  */
      if (stoped==0) { 

/* 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;
  };

window.onfocus = unPauseOnFocusFunction;
window.onblur = pauseOnBlurFunction;
window.onload = startFunction;

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

[/code]
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 #5 of 5
Quote:
Originally Posted by tonychjr View Post

i tried replacing these in the code and there are no errors but the timer is not running...any ideas.
Code:
<button id="start" onclick="StartFunction()">Reset/Start</button>
<button id="stop" onclick="StopFunction()">  Stop  </button>
<button id="pause" onclick="PauseFunction()">pause</button>

\and\

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


Javascript executes from top to bottom of the page. Further, external scripts are dynamically inserted into the document and then executed.
Code:
<!DOCTYPE html />
<html>
  <head>
  <meta charset="utf-8" />
  <title></title>
  <!--the entire page grinds to a halt until this first external script is loaded and executed-->
  <script type="text/javascript" src="my_external1.js"></script>
  </head>
  <body>
    <!--this onclick event doesn't bind to it's function until after the page (and thus all the scripts) are completely loaded-->
    <div onclick="t_func"></div>
    <!--an internal script, executes second-->
    <script>
      //some script
    </script>
    <!--this script loads third and once again stops page rendering (though there isn't much left)
        It's also noteworthy that as far as the page is concerned, the three scripts are just one giant script that
        was downloaded in three parts-->
    <script type="text/javascript" src="my_external2.js"></script>
  </body>
</html>
<!--the onload and pageshow events trigger here-->
<!--the embedded events are bound (though some browsers only attempt to bind them just as they are triggered the first time IIRC)-->

Your problem was probably that you put the window.addEventListener(); at the top of the page. When the code tried to execute, it didn't find the function anywhere (after all, the javascript parser hasn't 'seen' that function yet). Since this is javascript, the binding is silently ignored and the code just does it's best to continue (actually, new browsers will have logged a console message telling you it failed).

The solution is to add the bindings at the bottom of the page.

@tom.slick
Code:
var x = document.getElementById('my_elem');
x.onclick = function () {};
The above method of binding events should be avoided for two reasons. The first is that it is outdated. The second (and more serious) is that there may be another function attached to that element by someone else's code. x.onclick will overwrite this event while x.addEventListener(); will simply attach a second event (both will execute when the event triggers). Third is that options to capture the event are possible and lastly, you can target non-HTML elements in the DOM. IE9+ supports addEventListener() while IE before 9 supports attachEvent() (in fact, attachEvent was the inspiration behind addEventListener). If you don't want to be bothered with compatibility, just use one of the many functions that solve this issue. Here's one:
Code:
function addEvent(obj, evType, fn, useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be attached");
  }
}

var x = document.getElementById('my_elem');
addEvent(x, 'click', my_func, false);

Edited by hajile - 9/1/13 at 4:47pm
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Coding and Programming
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Javascript: Start/Stop/Pause without buttons