I work in a building with restricted internest access so I want to create my own html file to keep track of my breaks. What I need is a script with a 15 minute timer that I can start by pressing a button. I also need a 60 minute one. Any code would be greatly appreciated.
Here you go. <!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="chrome=1" /> <title>15 Minutes Timeout</title> </head> <body> <button id=button>Set Timer</button> <div id=timer></div> <script> var Timer, TotalSeconds; function StartTimer() { CreateTimer('timer', 900); // 15 minutes 60 * 15 = 900 }; function CreateTimer(TimerID, Time) { Timer = document.getElementById(TimerID); TotalSeconds = Time; UpdateTimer(); window.setTimeout(function() { Tick(); }, 1000); } var Tick = function() { if (TotalSeconds <= 0) { return; } TotalSeconds -= 1; UpdateTimer(); window.setTimeout(function() { Tick(); }, 1000); }; function UpdateTimer() { var Seconds = TotalSeconds; var Minutes = Math.floor(Seconds / 60); Seconds -= Minutes * (60); Timer.innerHTML = 'You\'ve got <span style="color:red;">' + LeadingZero(Minutes) + ':' + LeadingZero(Seconds) + '</span> minutes left.'; } function LeadingZero(Time) { return (Time < 10) ? '0' + Time : + Time; } var button = document.getElementById('button'); button.addEventListener('click', StartTimer, false); </script> </body> </html> Code (markup):
@ketting00 -- I always laugh when I see code like this: var Seconds = TotalSeconds; var Minutes = Math.floor(Seconds / 60); Seconds -= Minutes * (60); Code (markup): When you declare multiple VAR in a row, you don't need to say var as you can comma delimit them. Also, there's a reason we have the modulo (%) operator. Also, starting with a capital letter implies those are classes, not variables var minutes = Math.floor(totalSeconds / 60), seconds = totalSeconds % 60; Code (markup): Functionally identical... well, apart from executing faster thanks to using less operations. It's also sloppy to use innerHTML since that results in a reflow/re-render. That's why we're SUPPOSED to be using the DOM... and since you don't have a FORM it's inappropriate to use BUTTON... and since those elements don't work without scripting it's wrong for them to be in the markup... and those HTML 3.2 style attributes really shouldn't be blowing up anyone's skirts either. Just saying...
@deathshadow Your suggestions should be noted. It's good to be learning. Should I also write something like this to make my code look more modern: document.getElementById('button').addEventListener('click', function() { createTimer('timer', 900); }); Code (markup):