JSFiddle - React, Tailwind, and code Playground
by mariomc
HTML
<div id="red"></div>
<button type="button" onclick="expensiveFunction()">Calculate</button>
CSS
#red {
background-color:red;
border-radius: 100%;
position:absolute;
top:100px;
left:0px;
width:10px;
height:10px;
transform: translateX(-10px);
}
JavaScript
// Worker Helper Function here: https://medium.com/@dee_bloo/make-multithreading-easier-with-inline-web-workers-a58723428a42
// In production, use a separate file
function createWorker(fn) {
const blob = new Blob(['self.onmessage = ', fn.toString()], { type: 'text/javascript' });
const url = URL.createObjectURL(blob);
return new Worker(url);
}
const worker = createWorker(function (e) {
// Refactored expensiveFunction to be pure so it can live inside a worker
// Further optimization could be done if we pass the target as argument and memoize it
function expensiveFunction(){
let count=0;
const target = 1e9;
for(let i=0;i<=target;i++){
count++;
};
return count;
}
// Changed obtain the result
const result = expensiveFunction();
// Send it as a message to the parent thread
self.postMessage(result);
});
function expensiveFunction() {
// Send message to initiate calculation. We could change the worker to pass arguments
worker.postMessage('hey');
// Respond to the result by logging the data
worker.onmessage = a => console.log(a.data)
}
// ball animation
(function(){
const el = document.querySelector("div");
let left=0;
function step(){
el.style.transform = `translateX(${left++}px)`;
if( left > window.innerWidth + 10 ){
left=-10;
}
window.requestAnimationFrame( step );
}
window.requestAnimationFrame( step );
})();