The following snippet of code freezes the CSS animation until it is done. I can't figure out why. I tried promises, async await, setTimeout, nothing changed. I want to have nice and simple loading animation to show in the browser while the following snippet of code does its stuff behind the scenes. But it freezes my animation. What should I do?
sortedByFrequency is an object that contains large amount of word-properties which have digit values. The following methods sort properties inside the object highest value)
const sortedByFrequency = Object.entries(dictionary)
.sort(([, v1], [, v2]) => v2 - v1)
.reduce((obj, [k, v]) => ({
...obj,
[k]: v
}), {})
For "heavy" javascript calculations in browser it's recommended to use a web worker. It runs on its own process (that's why it needs its own js file). You communicate with it asynchronously, and there's really not much to it other than that.
my-worker.js
onmessage = function(e) {
console.log('Worker: Message received from main script');
var dictionary = e.data;
const sortedByFrequency = Object.entries(dictionary)
.sort(([, v1], [, v2]) => v2 - v1)
.reduce((obj, [k, v]) => ({
...obj,
[k]: v
}), {})
console.log('Worker: Posting message back to main script');
postMessage(sortedByFrequency);
}
main.js
var myWorker = new Worker("my-worker.js");
var dictionary = {a: 2, b: 3}
myWorker.postMessage(dictionary);
console.log('Message posted to worker');
myWorker.onmessage = function(e) {
var sortedByFrequency = e.data;
console.log('Message received from worker', sortedByFrequency);
}
Good luck.