Today I met the world of Web Workers in JavaScript. It made me think about timers. I used an ugly way for programming timers like this.
var time = -1; function timerTick() { time++; setTimeout("timerTick()",1000); $("#timeI").html(time); }
I know that this can be improved by keeping the timer running date, but I have never been a fan of this.
Now I came up with a method using Web Workers, I did a little test and found it much more reliable. Since I am not a JavaScript expert, I would like to know if this function works correctly or what problems it might get in advance.
My JavaScript code (note that I'm using jQuery):
$(function() { //-- Timer using web worker. var worker = new Worker('scripts/task.js'); //External script worker.onmessage = function(event) { //Method called by external script $("#timeR").html(event.data) }; };
External script ('scripts / task.js'):
var time = -1; function timerTick() { time++; setTimeout("timerTick()",1000); postMessage(time); } timerTick();
You can also watch a live demo on my site .
source share