If you don’t know about web workers learn them here: https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers
Disclaimer: Might not follow strict coding standards, this is just a demo.
This post basically shows how you can use webworkers to display a timer. For this I will be using the following files:
a. index.php
b. worker.js
Inside your index.php, lets write some javascript.
[code language=”javascript”]
<script>
var worker = null;
function createWorkers() {
if(worker == null){
// this needs to be in a different file
// worker always has to have a separate file
worker = new Worker("js/worker.js");
}
// add a listener here. this is needed, if you receive any data from the worker thread, you can handle it here
worker.addEventListener(‘message’, function(e) {
// I am using -1 to indicate that the timer has finished, you can use anything you want.
if(parseInt(e.data) == -1){
alert(‘Your time is finished’);
// exit the thread
$(‘#polling’).trigger(‘click’);
}else{
// update your timer text here. This is used to display the countdown timer
$("#timer span").text(e.data);
}
}, false);
}
$(document).on(‘click’, ‘#startTimer’, function(){
// create the workers here
createWorkers();
$.ajax(
{
url : "",
type: "GET",
data : getData,
success:function(data, textStatus, jqXHR)
{
if(data.data) {
// convert minutes into proper format
min = $("#timer").val() + ":00";
var totalTime = $("#timer").val();
// send a message
worker.postMessage("timer:"+totalTime);
}
});
</script>
<html>
<input type=button id=startTimer value=startTimer/>
<div class=timer id=timer value=""><span>10:00</span></div>
</html>
// inside worker.js
var totalTimeLimit = 0;
var timerVar = null;
var timerStart = true;
function timer(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;
// check if you have crossed the timer limit
if(parseInt(minutes) >= parseInt(totalTimeLimit)) {
// very important, to clear the timeout, else the threads keep
// on running, and eventually you are going to crash the browser
clearTimeout(timerVar);
self.postMessage("-1");
}else{
// 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;
}
self.postMessage(minutes+ ":" +seconds);
}
}
self.addEventListener(‘message’, function(e) {
var arr = e.data.split(":");
// you can use message to send different options
if(arr.length > 1){
if(arr[0] == "timer"){
if (timerStart){
totalTimeLimit = arr[1];
// get current time
var startTime =(new Date()).valueOf();
timerVar = setInterval( function(){
timer (startTime)
},1000);
timerStart = false;
}
}else if(arr[0] == "option2"){
// split it according what you want
var ids = arr[1].split(",");
var xmlhttp = new XMLHttpRequest();
// if (ids[2].XMLHttpRequest)
// {
// // code for IE7+, Firefox, Chrome, Opera, Safari
// xmlhttp=new XMLHttpRequest();
// }
// else
// {
// // code for IE6, IE5
// xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
// }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// send success message
}
}
var params = "";
// ideally use xmlHttp, since $ will give you undefined, unless passed through from
// the parent thread
xmlhttp.open("POST","http://localhost/data.json",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
}
}, false);
[/code]
Leave a Reply