Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save abhi9bakshi/02b0b0241c23a46bd86baaf5e9548db0 to your computer and use it in GitHub Desktop.
Save abhi9bakshi/02b0b0241c23a46bd86baaf5e9548db0 to your computer and use it in GitHub Desktop.
Javascript Timer using Web Worker (Async Timer)
// index.html
<p id="timer">
00:00:00
</p>
<button onClick="hangTheBrowser()">
Hang the browser
</button>
/* ---- */
// script.js
var worker = new Worker('worker.js');
worker.addEventListener('message', function(e) {
$('#timer').text(e.data);
});
worker.postMessage('run the timer');
function hangTheBrowser() {
let val = "";
for(let i=0; i<10000; i++){
for(let j=0; j<10000; j++) {
val = "Loop returned: " + i + j;
}
}
}
/* ---- */
// worker.js
self.addEventListener('message', function(e) {
if(e.data === 'run the timer') {
let count = 0;
setInterval(_ => {
count+=10;
let ms = count % 1000;
let s = Math.floor((count / 1000)) % 60;
let m = Math.floor((count / 60000)) % 60;
let time = m + ":" + s + ":" + ms;
self.postMessage(time);
}, 10);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment