Skip to content

Instantly share code, notes, and snippets.

@photomz
Created January 30, 2024 03:00
Show Gist options
  • Save photomz/3dbc316363ae9bbe6446a5c1a0a0a9a4 to your computer and use it in GitHub Desktop.
Save photomz/3dbc316363ae9bbe6446a5c1a0a0a9a4 to your computer and use it in GitHub Desktop.
Web Workers w/ Library Dependencies
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Web Worker Sorting Example</title>
</head>
<body>
<button id="startButton">Sort on worker thread</button>
<p>Sorted Numbers:</p>
<ul id="sortedList"></ul>
<script>
const startButton = document.getElementById('startButton');
const sortedList = document.getElementById('sortedList');
startButton.addEventListener('click', () => {
const numbers = generateRandomNumbers(20); // You can change the number of elements as needed
const worker = new Worker('worker.js');
worker.onmessage = (e) => {
const sortedNumbers = e.data;
displaySortedNumbers(sortedNumbers);
worker.terminate();
};
worker.postMessage(numbers);
});
function generateRandomNumbers(count) {
const numbers = [];
for (let i = 0; i < count; i++) {
numbers.push(Math.floor(Math.random() * 100)); // Generate random numbers between 0 and 99
}
return numbers;
}
function displaySortedNumbers(numbers) {
sortedList.innerHTML = '';
numbers.forEach((number) => {
const listItem = document.createElement('li');
listItem.textContent = number;
sortedList.appendChild(listItem);
});
}
</script>
</body>
</html>
// eslint-disable-next-line no-undef
importScripts('https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js'); // Import Lodash lib
onmessage = function (e) {
const numbers = e.data; // Get the numbers from the main thread
console.log('Worker: ' + numbers);
const sortedNumbers = _.sortBy(numbers); // Lodash lib passed as object arg from main thread
postMessage(sortedNumbers); // Send the sorted numbers back to the main thread
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment