0
0
Angularframework~30 mins

Web workers for heavy computation in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Web workers for heavy computation
📖 Scenario: You are building an Angular app that calculates the sum of a large list of numbers. To keep the app responsive, you will use a web worker to do the heavy calculation in the background.
🎯 Goal: Create an Angular standalone component that uses a web worker to sum numbers without freezing the UI.
📋 What You'll Learn
Create a list of numbers in the component
Add a threshold variable to control the number of items to sum
Use a web worker to calculate the sum of numbers up to the threshold
Display the result in the component template
💡 Why This Matters
🌍 Real World
Web workers help keep web apps responsive by running heavy tasks in the background, like processing large data sets or complex calculations.
💼 Career
Understanding web workers is useful for frontend developers to improve app performance and user experience, especially in Angular projects.
Progress0 / 4 steps
1
Create the numbers list
In the Angular component, create a variable called numbers and set it to an array containing the numbers from 1 to 1000.
Angular
Need a hint?

Use Array.from with length 1000 and map each index i to i + 1.

2
Add the threshold variable
Add a variable called threshold and set it to 500 in the component class.
Angular
Need a hint?

Just add threshold = 500; inside the class.

3
Use a web worker to sum numbers
Create a web worker instance called worker using new Worker() with the path './sum.worker'. Then add a method called startSum() that sends a message to the worker with the numbers sliced up to threshold. Also add an event listener to worker.onmessage that sets a variable result to the received data.
Angular
Need a hint?

Use new Worker(new URL('./sum.worker', import.meta.url)) to create the worker. Use postMessage to send data and onmessage to receive the result.

4
Complete the template to show result and start calculation
Update the component template to include a button with (click) event bound to startSum(). Also add a paragraph that shows Sum result: {{ result }}. Make sure the template is inside the template property of the @Component decorator.
Angular
Need a hint?

Use a button with (click)="startSum()" and a paragraph with interpolation {{ result }}.