Jump to content

Help on timing event


terryds

Recommended Posts

Hey, everyone. :DCould you please help me on making a timer with a stop and resume function ?Look at this

 <!DOCTYPE html><html><body> <p>A script on this page starts this clock:</p><p id="demo"></p><button onclick="myStopFunction()">Stop time</button> <script>var myVar=setInterval(function(){myTimer()},1000);function myTimer(){var d=new Date();var t=d.toLocaleTimeString();document.getElementById("demo").innerHTML=t;}function myStopFunction(){clearInterval(myVar);}</script> </body></html>

That's a timer with a stop function.. Please tell me how to resume the timer ? :D

Link to comment
Share on other sites

Hello, I just had a play around with your script and got it working, although when you resume the clock, it goes straight to the present time, as you could guess. If you stop it at 08:33:20 and leave it for 40s it will display 08:34:00. Not sure if you want it to resume from the time it was stopped? Here is the code:

<body> <p>A script on this page starts this clock:</p><p id="demo"></p><button onclick="myStartFunction()">Start time</button><button onclick="myStopFunction()">Stop time</button> <script>var myVar=setInterval("myTimer()",1000);function myTimer(){	var d=new Date();	var t=d.toLocaleTimeString();	document.getElementById("demo").innerHTML=t;}function myStopFunction(){	clearInterval(myVar);} function myStartFunction(){   myVar = setInterval("myTimer()",1000);}  </script>  </body>

It probably needs cleaning up but it works! :) Kind regards Lab.

Edited by Labtec
Link to comment
Share on other sites

Good news. Ok i'll have to have little play around as I'm not 100% in Javascript. Hopefully, someone can come and help you in the meantime. I don't think it is much work, maybe just saving the time at which it was stopped, then when resuming, comparing the difference to the current time and then subtracting it off the current time. If I remember JS is a little complicated when dealing with the crossover of days. I'll have a go but I reckon someone will post an answer before I get a chance to get it working. I will have a go at it right now. Regards, Labb

Link to comment
Share on other sites

  • 2 weeks later...

You need variables to keep track of the time that you started the timer most recently, and the elapsed time. Whenever you start the timer copy the current time into the start time variable. When you stop the timer, get the current time minus the start time, and add that to the elapsed time variable. When you display the timer you take the current time, minus the start time, plus the elapsed time, and that's the value you display for the timer.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...