js/quiz: workers, micro and macro tasks (#456)

This commit is contained in:
Vikas yadav 2024-06-06 07:05:39 +05:30 committed by GitHub
parent 9a99bb714b
commit 04584f6ed4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 354 additions and 0 deletions

View File

@ -0,0 +1,131 @@
---
title: What are microtasks and macrotasks?
---
## TL;DR
In JavaScript, tasks are managed by the event loop and are categorized into:
1. **Macrotasks**:
- Higher-level events like script execution, user interactions, timers, etc.
- Added to the macrotask queue and executed one by one.
2. **Microtasks**:
- Lower-level tasks like promise handlers, mutation observers, etc.
- These have higher priority and are executed immediately after the current script but before any macrotask.
### Event Loop Steps:
- Execute the current macrotask.
- Process all microtasks.
- Render updates (in a browser).
- Pick the next macrotask and repeat.
```js
console.log('start'); // script
setTimeout(() => console.log('setTimeout'), 0); // macrotask
Promise.resolve().then(() => console.log('Promise')); // microtask
console.log('end'); // script
// output
// start
// end
// Promise
// setTimeout
```
---
## Macrotask and microtask in JavaScript
In JavaScript, microtasks and macrotasks are two types of tasks that are managed by the event loop, which is responsible for executing code, handling events, and managing asynchronous operations
### Macrotasks
Macrotasks, also known as tasks, include operations that are queued in the event loop's `task queue`. These tasks are generally more substantial and can include:
- setTimeout(callback, delay)
- setInterval(callback, delay)
- setImmediate(callback) (Node.js only)
- I/O operations (e.g., file system operations in Node.js, network requests)
- UI rendering and other browser-specific tasks
When the event loop processes the macrotask queue, it picks and executes the tasks one by one. After a macrotask completes, the event loop checks the microtask queue first and processes any microtasks before moving on to the next macrotask. So macrotasks have lower priority than microtasks.
```js
console.log('Script start');
setTimeout(() => {
console.log('setTimeout callback');
}, 0);
console.log('Script end');
// Output:
// Script start
// Script end
// setTimeout callback
```
### Microtasks
Microtasks are smaller tasks that are usually executed immediately after the currently executing script and before any macrotask is executed. Microtasks typically include:
- Promises (e.g., Promise.then and Promise.catch callbacks)
- `MutationObserver` callbacks
- `queueMicrotask` (callback)
Microtasks are generally intended for short, quick tasks that need to be executed soon after the current operation completes. They have a higher priority than macrotasks, meaning they are executed before the event loop moves on to the next macrotask.
```js
console.log('Script start');
Promise.resolve()
.then(() => console.log('Promise microtask'))
.catch((err) => console.error(err));
console.log('Script end');
// Output:
// Script start
// Script end
// Promise microtask
```
### Event Loop Process
The event loop follows this order of execution:
- Execute the current macrotask.
- Execute all microtasks in the microtask queue.
- Render any updates (if applicable).
- Move on to the next macrotask.
This process repeats until there are no more tasks to execute
```js
console.log('Script start');
setTimeout(() => console.log('setTimeout'), 0);
queueMicrotask(() => console.log('queueMicrotask microtask'));
console.log('Script end');
// Output:
// Script start
// Script end
// queueMicrotask microtask
// setTimeout
```
The key difference is that microtasks have a higher priority than macrotasks and are executed immediately after the current macrotask, before rendering or moving on to the next macrotask. This allows for more precise and responsive handling of asynchronous operations, such as promises
## Further reading
- [The event loop - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop)
- [Tasks, microtasks, queues and schedules](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/)
- [Unraveling Macrotasks and Microtasks in JavaScript: What Every Web Developer Should Know](https://dev.to/bymarsel/unraveling-macrotasks-and-microtasks-in-javascript-what-every-developer-should-know-53mc)
- [https://javascript.info/event-loop](https://javascript.info/event-loop)

View File

@ -0,0 +1,11 @@
{
"slug": "what-are-microtasks-and-macrotasks",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": ["javascript"],
"importance": "high",
"difficulty": "medium"
}

View File

@ -0,0 +1,201 @@
---
title: What are workers in javascript used for?
---
## TL;DR
Workers in JavaScript are background threads that allow you to run scripts in parallel with the main execution thread, without blocking or interfering with the user interface.
### Key features
- **Parallel Processing** : Workers run in a separate thread from the main thread, allowing your web page to remain responsive to user interactions while the worker performs its tasks.
- **Communication** : Uses `postMessage` and `onmessage` for messaging.
- **Access to Web APIs**: Workers have access to various Web APIs, including `Fetch` API, `IndexedDB`, and `LocalStorage`, allowing them to perform tasks like data fetching and persisting data independently.
- **No DOM Access** : Workers cannot directly manipulate the `DOM` or interact with the `UI`, ensuring they don't accidentally interfere with the main thread's operation.
There are two main types of workers:
### Web workers
- Run scripts in background threads, separate from the main `UI` thread.
- Useful for CPU-intensive tasks like data processing, calculations, etc.
- Cannot directly access or manipulate the `DOM`.
### Service Workers:
- Act as network proxies, handling requests between the app and network.
- Enable offline functionality, caching, and push notifications.
- Run independently of the web app, even when it's closed.
---
## Workers in JavaScript
Workers in JavaScript are a way to run scripts in background threads, separate from the main execution thread of a web page. This allows for long-running or computationally intensive tasks to be offloaded from the main thread, preventing the user interface from becoming unresponsive or janky.
## Types of Workers
#### Web Workers
- Run scripts in background threads separate from the main `UI` thread
- Designed for CPU-intensive tasks like data processing, computations, etc.
- Cannot directly access the `DOM` or other main thread resources for security
- Communicate with main thread via asynchronous message passing
- Terminated when main script is unloaded or explicitly terminated
#### Use cases for web worker :
- Image/video processing
- Data compression
- Complex math
#### Creating a Web Worker
To create a web worker, you need a separate JavaScript file that contains the code for the worker. Heres an example:
**main.js (main script)**
```js
// Check if the browser supports workers
if (window.Worker) {
// Create a new Worker
const myWorker = new Worker('worker.js');
// Post a message to the worker
myWorker.postMessage('Hello, Worker!');
// Listen for messages from the worker
myWorker.onmessage = function (event) {
console.log('Message from Worker:', event.data);
};
// Error handling
myWorker.onerror = function (error) {
console.error('Error from Worker:', error);
};
}
```
**worker.js (worker script)**
```js
// Listen for messages from the main script
onmessage = function (event) {
console.log('Message from Main Script:', event.data);
// Perform a task (e.g., some computation)
const result = event.data + ' - Processed by Worker';
// Post the result back to the main script
postMessage(result);
};
```
In this example:
- `main.js` creates a worker using the `Worker` constructor and specifies `worker.j`s as the script to run in the worker thread.
- It posts a message to the worker using `postMessage`.
- The worker script (`worker.js`) listens for messages from the main script using `onmessage`.
- After processing the message, the worker posts a message back to the main script using `postMessage`.
- The main script listens for messages from the worker using `onmessage` on the `Worker` instance.
### Service Workers
- Act as a network proxy between web app, browser, and network
- Can intercept and handle network requests, cache resources
- Enable offline functionality and push notifications
- Have a lifecycle managed by the browser (install, activate, update)
- Limited access to `DOM` and main thread resources for security
#### Use cases for service workers:
- Caching
- Offline support
- Request handling
- Background sync
#### Creating a service Worker
**In main.js (main script)**
```js
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/service-worker.js')
.then(function (registration) {
console.log('Service Worker registered:', registration);
})
.catch(function (err) {
console.log('Service Worker registration failed:', err);
});
}
```
**service-worker.js (service worker script)**
```js
self.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request).then(function (response) {
// return cached response if available
if (response) {
return response;
}
// Otherwise, fetch from network
return fetch(event.request);
}),
);
});
```
In this example:
- The main script registers a `Service worker` at `/service-worker.js`.
- The Service worker listens for the `fetch` event, which is fired whenever the browser makes a network request.
- The Service worker first checks if the requested resource is cached using `caches.match(event.request)`.
- If it is, it returns the cached response. Otherwise, it fetches the resource from the network using `fetch(event.request)`.
### Shared Workers
- Can be accessed from multiple scripts in different windows/tabs/iframes
- Allow data sharing between browser contexts via a messaging interface
- Similar to dedicated Web Workers but with a broader scope
### Use cases for service workers:
- State sharing across multiple windows
### Worklets
- Lightweight workers for specific use cases like painting, audio processing
- Run in separate threads from main UI thread
- Provide a way to extend browser rendering engines with custom logic
- **Types**: Animation Worklets, Audio Worklets, Layout Worklets, Paint Worklets
### Use cases for worklet:
- Custom CSS animations
- Audio effects
- Layout calculations
The key differences lie in their intended purposes, scope, and access to browser APIs. Web Workers are for CPU-intensive tasks, Service Workers handle network requests and offline, Shared Workers enable cross-window communication, and Worklets extend browser rendering capabilities.
## Considerations and Limitations
- **Same-Origin Policy**: Workers must comply with the same-origin policy, meaning the script that creates the worker and the worker script itself must be from the same origin.
- **No DOM Access**: Workers do not have direct access to the DOM. They can communicate with the main thread through messages.
- **Performance**: Creating and managing workers incurs overhead. They should be used judiciously for tasks that truly benefit from parallel execution.
- **Error Handling**: Proper error handling mechanisms should be in place to handle any issues within the worker scripts.
## Conclusion
Workers in JavaScript are a powerful tool for improving the performance and responsiveness of web applications by offloading time-consuming tasks to background threads. They enable more efficient and smoother user experiences, especially for applications requiring heavy computations or asynchronous processing. By understanding and utilizing workers effectively, developers can create more robust and high-performing web applications.
## Further reading
- [Worker - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Worker)
- [Using Web Workers - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
- [Service Worker API - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)
- [Understanding web workers in JavaScript with real world example ](https://javascript.plainenglish.io/understanding-web-workers-in-js-with-real-world-example-1629a283aeec?gi=89cf0dd4c3f4)
- [Web worker, Service worker, and Worklets: A comprehensive guide](https://dev.to/bharat5604/web-worker-service-worker-and-worklets-a-comprehensive-guide-1f64)

View File

@ -0,0 +1,11 @@
{
"slug": "what-are-workers-in-javascript-used-for",
"languages": [],
"companies": [],
"premium": false,
"duration": 5,
"published": true,
"topics": ["javascript"],
"importance": "high",
"difficulty": "medium"
}