Timers

Objectives

Using timers

Example of setTimeout

Live version at date4.html

<!DOCTYPE html> <html lang="en"> <head> <title></title> <script> function pad(str, cols, ch) { while ((""+str).length < cols) str = ch + str; return str; } function displayTime() { var militaryformat = false; if (document.clock.timeformat[0].checked) { militaryformat = true; } var now = new Date(); var hours = now.getHours(); var ampm = ""; if (!militaryformat) { if (hours >= 12) ampm = " pm"; else ampm = " am"; if (hours == 0) hours = 12; else if (hours > 12) hours -= 12; } document.clock.display.value = hours + ':' + pad(now.getMinutes(), 2, '0') + ':' + pad(now.getSeconds(), 2, '0') + ampm; setTimeout(displayTime,1000); } window.onload = displayTime; </script> </head> <body> <form name="clock" action="#"> <p align="center"><input type="text" readonly="readonly" name="display" /></p> <p align="center"> Military time? <input type="radio" name="timeformat" checked="checked" /> Yes &#160;&#160; <input type="radio" name="timeformat" /> No </p> </form> </body> </html>

Example of setInterval and clearInterval

Live version at date8.html

<!DOCTYPE html> <html lang="en"> <head> <title></title> <script> function pad(str, cols, ch) { while ((""+str).length < cols) str = ch + str; return str; } function displayTime() { var militaryformat = false; if (document.clock.timeformat[0].checked) { militaryformat = true; } var now = new Date(); var hours = now.getHours(); var ampm = ""; if (!militaryformat) { if (hours >= 12) ampm = " pm"; else ampm = " am"; if (hours == 0) hours = 12; else if (hours > 12) hours -= 12; } document.clock.display.value = hours + ':' + pad(now.getMinutes(), 2, '0') + ':' + pad(now.getSeconds(), 2, '0') + ampm; } window.onload = function() { displayTime(); var timer = setInterval(displayTime, 1000); document.getElementById('btnStop').onclick = function() { clearInterval(timer); }; }; </script> </head> <body> <form name="clock" action="#"> <p align="center"><input type="text" readonly="readonly" name="display" /></p> <p align="center"> Military time? <input type="radio" name="timeformat" checked="checked" /> Yes &#160;&#160; <input type="radio" name="timeformat" /> No </p> <p><button type="button" id="btnStop">Stop clock</button></p> </form> </body> </html>