In this post, we will implement a simple JavaScript timer, using Web Workers in HTML5. The advantage of Web Workers is that it will run in the background without affecting the performance or your page.
A simple timer:
00:00
Code :::
simple-timer.html:
<!DOCTYPE html><html lang="en"><head> <meta charset="utf-8" /> <title>Timer</title> </head><body> <div class="header">A simple timer:</div> <div class="timer" id="timer">00:00</div> <div class="buttons"> <button onclick="startTimer()" id="button1">Start</button> <button onclick="stopTimer()" id = "button2">Stop</button> </div></body><script>var w = null; // initialize variable// function to start the timerfunction startTimer(){ // First check whether Web Workers are supported if (typeof(Worker)!=="undefined"){ // Check whether Web Worker has been created. If not, create a new Web Worker based on the Javascript file simple-timer.js if (w==null){ w = new Worker("simple-timer.js"); } // Update timer div with output from Web Worker w.onmessage = function (event) { document.getElementById("timer").innerHTML = event.data; }; } else { // Web workers are not supported by your browser document.getElementById("timer").innerHTML = "Sorry, your browser does not support Web Workers ..."; }}// function to stop the timerfunction stopTimer(){ w.terminate(); timerStart = true; w = null;}</script></html>
var timerStart = true;function myTimer(d0){ // get current time var d=(new Date()).valueOf(); // calculate time difference between now and initial time var diff = d-d0; // calculate number of minutes var minutes = Math.floor(diff/1000/60); // calculate number of seconds var seconds = Math.floor(diff/1000)-minutes*60; var myVar = null; // if number of minutes less than 10, add a leading "0" minutes = minutes.toString(); if (minutes.length == 1){ minutes = "0"+minutes; } // if number of seconds less than 10, add a leading "0" seconds = seconds.toString(); if (seconds.length == 1){ seconds = "0"+seconds; } // return output to Web Worker postMessage(minutes+":"+seconds);} if (timerStart){ // get current time var d0=(new Date()).valueOf(); // repeat myTimer(d0) every 100 ms myVar=setInterval(function(){myTimer(d0)},100); // timer should not start anymore since it has been started timerStart = false;}