- In my previous post we have learn creating a dedicated worker.
- In this demo, “We will learn to create a dedicate worker for generating time with Hour,Minute and Second”.
- To develop this dedicated worker we have created 2 files dateWorker.js and dateWorkerDemo.html. The dateWorker.js file contains the code definition of the date worker. The dateWorkerDemo.html file contains the code to call the date worker.
- The following code shows the content dateWorker.js file.It contains a setInterval() method block called in every 1 second.This code block get current date and post the message wit a object containing hour,minute and second properties.
self.addEventListener("message",function(event){ setInterval(function(){ var time = new Date(); self.postMessage({ hour:time.getHours(), minute: time.getMinutes(), second: time.getSeconds() }); },1000); });
- The following code shows the content of dateWorkerDemo.html file.It contains a button Get Time and attached with a Click handler.The click handler post a message to get the time from worker.Once the response is received it displays the hour,minute and second in browser.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Time Web Worker Demo</title> </head> <body> <h1 id="resultContainer"></h1> <button id="timeButton">Get Time</button> <script> var dateWorker = new Worker("dateWorker.js"), resultContainer = document.getElementById("resultContainer"), timeButton = document.getElementById("timeButton"); timeButton.addEventListener("click",function(){ dateWorker.postMessage(null); }); dateWorker.addEventListener("message",function(workerEvent){ var responseData = workerEvent.data, hour = responseData.hour, minute = responseData.minute, second = responseData.second; resultContainer.innerText = "HOUR: "+hour + " MINUTE: "+minute +" SECOND: "+second; }); </script> </body> </html>
- The output of the code can be found in the following screenshot.
- The demo code can be found in the following Plunker link.