Skip to content

Instantly share code, notes, and snippets.

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