Web worker example
Author: q | 2025-04-23
HTML5 Web Workers. What is a Web Worker? HTML Web Workers Example. Check Web Worker Support. Create a Web Worker File. Create a Web Worker Object. Terminate a Web Worker. Reuse the Web Worker. Full Web Worker Example Code. Web Workers and the DOM. Examples. Lessons for beginners. W3Schools in English Web Workers Example. The example below creates a simple web worker that count numbers in the background:
GitHub - bespoyasov/web-worker-example: Using Web Workers
The language and creates a default web process type to boot the application server. However, creating an explicit Procfile is recommended for greater control and flexibility over your app.For Heroku to use your Procfile, add the Procfile to the root directory of your application, then push to Heroku:$ git add .$ git commit -m "Procfile"$ git push heroku master...-----> Procfile declares process types: web, worker Compiled slug size is 10.4MB-----> Launching... done deployed to HerokuTo git@heroku.com:strong-stone-297.git * [new branch] master -> masterUse heroku ps to determine the number of dynos that are executing. The list indicates the process type in the left column, and the command corresponding to that process type in the right column:$ heroku ps=== web: `bundle exec rails server -p $PORT`web.1: up for 2mUse heroku logs to view an aggregated list of log messages from all dynos across all process types.$ heroku logs2011-04-26T01:24:20-07:00 heroku[slugc]: Slug compilation finished2011-04-26T01:24:22+00:00 heroku[web.1]: Running process with command: `bundle exec rails server mongrel -p 46999`2011-04-25T18:24:22-07:00 heroku[web.1]: State changed from created to starting2011-04-25T18:24:29-07:00 heroku[web.1]: State changed from starting to up2011-04-26T01:24:29+00:00 app[web.1]: => Booting Mongrel2011-04-26T01:24:29+00:00 app[web.1]: => Rails 3.0.5 application starting in production on app[web.1]: => Call with -d to detach2011-04-26T01:24:29+00:00 app[web.1]: => Ctrl-C to shutdown serverScaling a process typeHeroku runs one web dyno for you automatically, but other process types don’t start by default. To launch a worker, you need to scale it up to one dyno:$ heroku ps:scale worker=1Scaling worker processes... done, now running 1You can also scale the size of a dyno:$ heroku ps:resize worker=standard-2xResizing dynos and restarting specified processes... doneworker dynos now standard-2xCheck ps to see the new process type running, for example:$ heroku ps=== web: `bundle exec rails server -p $PORT`web.1: up for 2m=== worker: `env QUEUE=* bundle exec rake resque:work`worker.1: up for 5sUse heroku logs --ps worker to view just the messages from the worker process type:$ heroku logs --ps worker2011-04-25T18:33:25-07:00 heroku[worker.1]: State changed from created to starting2011-04-26T01:33:26+00:00 heroku[worker.1]: Running process with command: `env QUEUE=* bundle exec rake resque:work`2011-04-25T18:33:29-07:00 heroku[worker.1]: State changed from starting to up2011-04-26T01:33:29+00:00 app[worker.1]: (in /app)The output we see here matches our local output, interleaved with system messages from Heroku’s system components such as the router and dyno manager.You can scale up higher with the same command. For example, two web dynos and four worker dynos:$ heroku ps:scale web=2 worker=4Scaling web processes... done, now running 2Scaling worker processes... done, now running 4$ heroku ps=== web: `bundle exec rails server -p $PORT`web.1: up for 7mweb.2: up for 2s=== worker: `env QUEUE=* bundle exec rake resque:work`worker.1: up for 7mworker.2: up for 3sworker.3: up for 2sworker.4: up for 3sRead more about scaling.More process type examplesThe Procfile model of running processes types is extremely flexible. You can run any number of dynos with whatever arbitrary commands you want, and scale each independently.For example, using Ruby you could run two types of queue workers, each consuming different queues, as well as a release phase command:release: ./release-tasks.shworker: env QUEUE=* bundle exec rake resque:workurgentworker: env QUEUE=urgent bundle exec rake resque:workThese can then be
dom-examples/web-workers/simple-web-worker/index.html at
IntroductionWeb workers are a powerful feature in modern browsers that allow JavaScript to spawn background threads and perform resource-intensive tasks asynchronously without blocking the main UI thread. This helps ensure smooth and responsive user experiences. In this comprehensive guide, we will cover the following topics:What are web workers and why are they useful?A practical example to demonstrate web workers Communicating between web workers and main UI threadBrowser support and fallback optionsPerformance considerations and best practicesCommon use cases for web workersBy the end, you‘ll have a solid understanding of how to leverage web workers to build high-performance web apps. Let‘s get started!What are Web Workers?Web workers provide a simple mechanism to run scripts in background threads separate from the main execution thread. Some key aspects:They allow long-running computations and I/O intensive operations without blocking the UIWeb workers run in another global context, don‘t have access to the DOMThey communicate with the main thread via message passing Created using new Worker() or new SharedWorker()Conceptually, you can think of web workers as a way to delegate heavy tasks to other threads running in parallel. The key advantage is the UI never gets blocked.For example, if you need to parse a huge local CSV dataset, that could lock up the browser for several seconds. With web workers, you can spin up a background thread to handle the parsing without impacting UI responsiveness.Diagram showing how web workers run on separate threads.Now that we know what web workers are, let‘s look at a practical example to see them in action.To demonstrate web workers, we will build a basic web app that fetches cryptocurrency prices every few seconds and displays them in a chart. Without workers, this would quickly become unusable as the main UI thread gets blocked each time we refresh the prices.Here is an overview of the app:Main UI thread with controls and chart Web worker thread that polls prices and sends messages Communication between the threads via postMessage()App Structure/- index.html- style.css- app.js|— /js - worker.js The key files are:app.js: Main application logic for UIworker.js: Web worker thread code Creating a Dedicated Web WorkerFirst, we need to spin up a web worker from the main app using the Worker constructor:// Create new workerconst worker = new Worker(‘./js/worker.js‘);This spawns a background thread and executes worker.js in a separate global context. Inside worker.js we can register handlers to receive and respond to messages:// Listen for messages from main threadself.addEventListener(‘message‘, (e) => { // .. worker logic here // Post back result self.postMessage(result);});For this app, the worker will poll new price data every few seconds and post messages back to the main thread.Main Thread LogicWith the worker setup, the main script app.js will have UI handlers to start/stop polling prices, render the chart, and process incoming messages:// Listen for messages from workerworker.addEventListener(‘message‘, (e) => { // Update chart with new prices updateChart(e.data); });// Handler to start polling prices startPollingBtn.addEventListener(‘click‘, () => { // Post message to start worker worker.postMessage({‘cmd‘: ‘start‘});});Here we listen for messages from the worker andAngular- web worker example - StackBlitz
Things You Can Do In A Web Workertldr; A list of available functionality and use cases for web workers. Have something to add? Submit a PR.Web Workers give web developers the apility to run code in multiple threads. This is great, now, what can we do with these threads? This document is meant to help provide context and real world use cases for these little wonders.ToolingA lot of your favorite tools have excellent support for web workers, making them even easier to use!RollupWebpackAvailable APISFileReaderThe file reader api allows you to read uploaded files.You can now upload a file (say csv). send that to a web worker, read the file and parse it to json without blocking the main UI thread.IndexedDB"IndexedDB is a way for you to persistently store data inside a user's browser. Because it lets you create web applications with rich query abilities regardless of network availability, your applications can work both online and offline."Web NotificationsWeb Notifications allow you to send pop up style notifications to users even when they do not have your site open.XMLHttpRequestLets you make a network request.FetchThe Fetch API is a modern replacement for XMLHttpRequest and is closer to a lot of the libraries we are used to.Web Sockets"WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply."USE CASESWeb Assembly (WASM)Web assembly is fully capable of being run inside of a web worker! This means we can do some more computationaly heavy tasks taking advantage of wasm but avoiding blocking our main UI thread. For an example take a look at this simple machine learning Tic Tac Toe bot written in Rust and running in wasm. large data sets without blocking the UI thread and without making a full round trip to the server. { const res = e.data.filter((item) => item.flagged); self.postMessage(res);};// app.jsvar filterWorker = new Worker('filter-worker.js');filterWorker.onmessage = function (e) { // Log filtered list console.log(e.data);}var hugeData = [ .... HTML5 Web Workers. What is a Web Worker? HTML Web Workers Example. Check Web Worker Support. Create a Web Worker File. Create a Web Worker Object. Terminate a Web Worker. Reuse the Web Worker. Full Web Worker Example Code. Web Workers and the DOM. Examples. Lessons for beginners. W3Schools in EnglishWeb Workers Example for the book - GitHub
Use the posted data to update the chart.The full main thread code is available in this CodePen.Web Worker ThreadNow inside worker.js we can poll the prices and post messages back to main thread:// CoinDesk BPI endpointconst apiUrl = ‘ Initialize prices let prices = {}; // Poll prices setInterval(async () => { // Fetch latest data const res = await fetch(apiUrl); prices = await res.json(); // Post back to main thread self.postMessage(prices);}, 3000); // 3sec intervalWe use setInterval to poll the API every few seconds, then post the updated prices back to the main thread.The full worker script code is available here.And that‘s it! Together the main thread and worker script coordinate to fetch data and update the UI without blocking.Here is a CodePen showing the full demo: See the Pen Web Worker Demo: Fetching API Data by Aravind (@aravindballa) on CodePen.Hopefully this gives a real-world example of leveraging web workers! 😊Communicating Between ThreadsAs seen above, the primary way for web workers to communicate with the main thread is by posting messages to each other.The main interface for this in both contexts is the postMessage() method. Along with the message content, you can specify message origins and transferrable objects.Some key mechanisms for thread communication:Main Thread -> Workerworker.postMessage(): Send message to worker worker.onmessage: Listen for messages from workerWorker Thread -> Main Thread self.postMessage(): Post messages back to main threadself.onmessage: Listen for messages from main threadAdditionally, web workers expose mechanisms like terminate() to end threads and handle errors.This abstracted message-passing approach allows you to coordinate between threads without worrying about low-level concurrency issues.Browser SupportMost major browsers have excellent support for web workers:However, some limitations exist:IE10 and below do not support web workers at all Safari support is more recent For cases when web workers are not supported, you can fallback to using Web Worker polyfills. Some popular options:WorkerizeWeb Worker ThreadsThese polyfills emulate worker threads by spawned separate processes. This ensures backwards capability while limiting concurrency.Performance ConsiderationsWhile web workers are quite useful, some care should be taken to use them efficiently: Memory overheads – Each worker has its own global context, so memory usage can add upThread contention – Creating too many workers could contend for limited browser threads Message passing costs – Serializing excessive large data back-and-forth has a costSome best practices include:Keep the number of active web workers reasonable (under 10)Pool/reuse workers instead of continuously creating new ones Pass small message data instead of entire huge objectsUse Comlink for optimized message passing Additionally, you should not use web workers for any browser-specific APIs like DOM manipulation, as they are not exposed to worker contexts.Common Use CasesHere are some common examples where web workers shine:Processing large local datasets (JSON, CSV, etc) Polling and streaming external APIsRunning expensive computations like image filters Periodic background syncs with serverPrefetching assets/data for later use Parsing multimedia files (audio, video, images)Spellchecking/grammar validation Essentially any CPU or I/O intensive tasks that could block the main UI thread are good fits for delegation to a web worker.ConclusionI hope thisWeb Workers Example With Angular - GitHub
CentreStackInstallationGuideBuild6.5.2033.325526/1/2015________________________________________________________________________Table of ContentsOverview of CentreStackDeployment DiagramStep 1: Prepare the File StorageStep 2: Prepare the Active Directory(Optional)Step 3: Prepare the Database ServerStep 4: Prepare the Worker NodesStep 5: Start InstallationStep 6: Initial ConfigurationStep 7: Check Out Web PortalStep 8: Check out the ManagementConsoleStep 9: Enable SSL – Install SSLCertificateStep 10: Set up Worker NodepropertiesStep 11: Verify External URL,Internal URL and Node NameVerify External URLVerify Internal URLVerify Node NameStep 12: Add the node to the LoadBalancerStep 13: Setup the Second Node(Worker Node #2)Option 1 – GUI SetupOption 2 – Command Line Script Setup13.1 – Preparation on the Worker Node#113.2 - Clone Program Files13.3 – Clone the Registry13.4 – Command Line Setup for the IISASP.NET and WCF applications.13.5 - Import SSL Certificate13.6 - Sanity Check Worker Node #213.7 – Add the worker node 2 to thecluster13.8 – Add the worker node #2 to theLoad Balancer.13.9 Pre-Compile ASP.NET PagesStep 14: Setup Worker Node #3BrandingSelf-Service BrandingFull-Branding ServiceUpgradeOption #1 – GUI Installer for UpgradeOption #2 – Command Line UpgradeStep 1 – Unzip the FolderStep 2 – Copy files over to theProgram Files. Overview of CentreStackCentreStackprovides value-added services on top of cloud storage services or local storageservices. Cloud Storage services include those from OpenStack Swift, Amazon S3and its compatibles, Google Cloud Storage, HP Cloud Storage and many others. LocalStorage Services include file server Storage, SAN or NAS storage. CentreStackvalue-added services can be summarized as Backup, Access,Sync and Share, Identity, Control andCollaboration (BASIC). The value-added services are also known asEnterprise File Sync and Share services (EFSS).CentreStack isa cluster of web services built on top of the Microsoft Web Platform. Itprovides the BASIC value-added services that facilitate onlinestorage access for PCs, Macs, File Servers, Web Browsers, and Mobile Devices.The servicescan be deployed in flexible combinations to meet different needs. For example,you can deploy it on premise as a private cloud or you can deploy itoff-premise in a data center, managed by your managed service provider (MSP) oryou can deploy it in Amazon EC2-like environment as virtual-private deployment.There are threedifferent types of machines (or Virtual Machines). In the smallest deploymentunit, the three different logical nodes can co-exist in one singleNext.js With Web Worker Example - StackBlitz
An external device (detected using Web USB, Web Bluetooth, WebHID, or Web Serial).Hold a Web Lock or an IndexedDB connection that blocks operationsoutside the group.The definition of "CPU-intensive" may evolve, but the intention is to excludeefficiently implemented email or chat clients, or calendar applications thatgenerate notifications.Freezing simultaneously all tabs within the same browsing context group minimizes disruptionfor apps that use popups, such as those for composing messages or enteringcredentials.How can I prepare my site?If your site doesn't have background functionality (for example notifications,file uploads, or content refresh), it likely won't be affected by freezing.If your site does have background functionality, minimize its CPU usage in thebackground to avoid being considered CPU-intensive and thus frozen. Here aresome tips:Avoid timers for periodic state change checks.UseIntersectionObserverto detect when an element enters the viewport.Use ResizeObserver to detectelement size changes.UseMutationObserveror custom element lifecyclecallbacksfor DOM changes.Consider websockets,server-sentevents, pushmessages, or fetchstreamsinstead of a polling server.Use events like timeupdate andended foraudio or video changes.We also recommend migrating background functionality to a service worker so thatit's not affected by freezing. In addition to not being affected by freezing, aservice worker requires less browser resources. Consider using:Push API for notificationsBackground SynchronizationAPIor Web Periodic Background SynchronizationAPI forfetching updates.Sites can opt out of freezing by participating in theBackgroundPageFreezeOptOut origin trial.This trial will be discontinued once new APIs for declaringimportant background work are released (for example the Progress NotificationAPI).You can check a tab's eligibility for freezing at chrome://discards. Note thateven if a tab is eligible for freezing, Chrome 133 will only freeze itAngular Web Worker Example - StackBlitz
Worker was registered on this origin,there's still a message saying there is no current service worker.That's because this page is not within the registered service worker's scope.Scope limits what pages the service worker controls.In this example, that means the service worker loaded from /subdir/sw.js can only control pages located in /subdir/ or its subtree.The above is how scoping works by default,but the maximum allowed scope can be overridden by setting theService-Worker-Allowed response header,as well as passing ascope option to the register method.Unless there's a very good reason to limit service worker scope to a subset of an origin,load a service worker from the root directory of the web server so that its scope is as broad as possible,and don't worry about the Service-Worker-Allowed header. It's a lot simpler for everyone that way.ClientWhen it's said that a service worker is controlling a page, it's really controlling a client.A client is any open page whose URL falls within the scope of that service worker.Specifically, these are instances of a WindowClient.The lifecycle of a new service workerIn order for a service worker to control a page,it must first be brought into existence, so to speak.Let's begin with what happens when a brand new service worker is deployed for a website with no active service worker.RegistrationRegistration is the initial step of the service worker lifecycle: // Don't register the service worker // until the page has fully loaded window.addEventListener('load', () => { // Is service worker available? if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').then(() =>. HTML5 Web Workers. What is a Web Worker? HTML Web Workers Example. Check Web Worker Support. Create a Web Worker File. Create a Web Worker Object. Terminate a Web Worker. Reuse the Web Worker. Full Web Worker Example Code. Web Workers and the DOM. Examples. Lessons for beginners. W3Schools in English Web Workers Example. The example below creates a simple web worker that count numbers in the background:
react-web-workers examples - CodeSandbox
Physics simulation return data * 2; // Example calculation}Invoke the Worker from the Main Thread: In your main WebGL script, you can invoke the Web Worker and pass data to it.const worker = new Worker('worker.js');worker.postMessage(100); // Send data to the workerworker.onmessage = function(event) { const result = event.data; console.log('Result from worker:', result);};By using Web Workers, you can offload complex computations and keep your WebGL application responsive, even when performing heavy calculations.11. Monitor and Debug WebGL PerformanceOptimization doesn’t stop once your application is built. Continuous monitoring and debugging are essential to ensure that your WebGL project maintains high performance, especially as you add new features or assets. Several tools and techniques can help you monitor performance in real-time and identify potential bottlenecks.WebGL Debugging Tools:Chrome DevTools: The Performance panel in Chrome DevTools allows you to capture and analyze frame rates, memory usage, and CPU/GPU activity. You can see how long each frame takes to render and identify potential issues such as high draw calls or inefficient shaders.Firefox Performance Tools: Firefox offers similar tools to profile WebGL applications, allowing you to track frame rates, memory usage, and WebGL draw calls.Three.js Inspector: If you’re working with Three.js, the Three.js Inspector Chrome extension is a valuable tool for debugging your scene. It lets you visualize the scene graph, inspect materials and shaders, and monitor performance metrics specific to your Three.js project.Profiling and Identifying Bottlenecks:When using these tools, focus on key performance metrics such as:Frame Rate: The ideal frame rate is 60 FPS for smooth interactions,simple-web-worker examples - CodeSandbox
On demand. Mobile workers can download a web map that has been configured for offline use and create their own offline areas in the Explorer app.Learn more about how to prepare maps for download and download maps and offline areas.Maintain situational awareness in the fieldThe ability to monitor your operations in near-real time is essential for making informed decisions and responding quickly to incidents as they happen. This is especially crucial in highly dynamic situations like public event or disaster response operations.Watch your maps come alive in Explorer by defining refresh intervals for your web maps in ArcGIS Online. These options keep your maps up-to-date with the latest information when there’s a data connection, providing you and your team with greater situational awareness.Refresh intervals automatically update your map layers at a specific time interval that you set. You can set your layers to update as often as every 6 seconds for most layer types!For example, you may want your team to be aware of each other’s location so that you can properly respond during a live event. You can do this by setting refresh intervals on a layer in your web map that contains the last known location of each mobile worker from the Tracker for ArcGIS application.Only authorized members of your team would be able to see each other’s locations. Your organization’s administrator would manage those permissions for your location tracking service. Learn more about tracking service privileges.Explorer would display the last known locations of your team members and keep it updated (when there is connectivity) based on the refresh interval that you set up.View tracks (iOS only)Now mobile workers can view their own tracks from the Tracker for ArcGIS app in Explorer on their iPhone or iPad device.This allows mobile workers to see a breadcrumb trail of where they’ve been. For example, a field worker may be inspecting damage in a disaster area which can be a highly disorienting situation. Viewing their tracks in Explorer along with the features in their map can help the field worker verify they covered the intended territory.Manage complex workflows with easier app. HTML5 Web Workers. What is a Web Worker? HTML Web Workers Example. Check Web Worker Support. Create a Web Worker File. Create a Web Worker Object. Terminate a Web Worker. Reuse the Web Worker. Full Web Worker Example Code. Web Workers and the DOM. Examples. Lessons for beginners. W3Schools in English Web Workers Example. The example below creates a simple web worker that count numbers in the background:HTML5 Web Workers example GitHub
Here are 11 public repositories matching this topic... Code Issues Pull requests ⚛️ useWorker() - A React Hook for Blocking-Free Background Tasks Updated Mar 9, 2025 JavaScript Code Issues Pull requests Simplest way to include web workers with your React Application and get smoother experience Updated Dec 11, 2022 JavaScript Code Issues Pull requests React hooks for running code inside web workers without needing to eject CRA apps. Updated May 19, 2021 TypeScript Code Issues Pull requests Example code for article - Optimizing Your Next.js App By Offloading Compute-Intensive Tasks from Main Thread to Web Workers Updated Mar 7, 2024 TypeScript Code Issues Pull requests Discussions fetch and process data in web worker, store in indexedDB. Updated Apr 3, 2023 TypeScript Code Issues Pull requests Discussions FreeScribe is a Machine Learning React Vite TailwindCSS Web Based Transcription & Translation App that uses Web Workers to run ML models in the browser. This app allows you to record your voice or upload an audio file (mp3/wav), transcribe it to text, translate it into any language, download/ copy the freshly converted text that has be transcribed. Updated Sep 7, 2024 JavaScript Code Issues Pull requests Easy-going multiplayer board game. Updated Nov 22, 2020 JavaScript Code Issues Pull requests Concurrent Rust / Wasm state container for web apps. Updated Jan 20, 2023 Rust Code Issues Pull requests A P2P File sharing system similar to Torrent, where users can seed[upload] or download files simultaneously. Currently I have implemented a browser based client in react js which utilizes web workers to paralelly upload/download files. Backend is implemented in Node Js. Entire application is powered by the magic of Socket Programming. Updated Jun 12, 2024 TypeScript Code Issues Pull requests Using embeddings from a pre-trained language model to provide semantic search capabilities in a combobox interface, directly in the browser. Updated Mar 3, 2025 TypeScript Code Issues Pull requests Discussions Web Workers with React, Brain.js, and other things Updated Apr 11, 2022 TypeScript Improve this page Add a description, image, and links to the web-worker-react topic page so that developers can more easily learn about it. Curate this topic Add this topic to your repo To associate your repository with the web-worker-react topic, visit your repo's landing page and select "manage topics." Learn moreComments
The language and creates a default web process type to boot the application server. However, creating an explicit Procfile is recommended for greater control and flexibility over your app.For Heroku to use your Procfile, add the Procfile to the root directory of your application, then push to Heroku:$ git add .$ git commit -m "Procfile"$ git push heroku master...-----> Procfile declares process types: web, worker Compiled slug size is 10.4MB-----> Launching... done deployed to HerokuTo git@heroku.com:strong-stone-297.git * [new branch] master -> masterUse heroku ps to determine the number of dynos that are executing. The list indicates the process type in the left column, and the command corresponding to that process type in the right column:$ heroku ps=== web: `bundle exec rails server -p $PORT`web.1: up for 2mUse heroku logs to view an aggregated list of log messages from all dynos across all process types.$ heroku logs2011-04-26T01:24:20-07:00 heroku[slugc]: Slug compilation finished2011-04-26T01:24:22+00:00 heroku[web.1]: Running process with command: `bundle exec rails server mongrel -p 46999`2011-04-25T18:24:22-07:00 heroku[web.1]: State changed from created to starting2011-04-25T18:24:29-07:00 heroku[web.1]: State changed from starting to up2011-04-26T01:24:29+00:00 app[web.1]: => Booting Mongrel2011-04-26T01:24:29+00:00 app[web.1]: => Rails 3.0.5 application starting in production on app[web.1]: => Call with -d to detach2011-04-26T01:24:29+00:00 app[web.1]: => Ctrl-C to shutdown serverScaling a process typeHeroku runs one web dyno for you automatically, but other process types don’t start by default. To launch a worker, you need to scale it up to one dyno:$ heroku ps:scale worker=1Scaling worker processes... done, now running 1You can also scale the size of a dyno:$ heroku ps:resize worker=standard-2xResizing dynos and restarting specified processes... doneworker dynos now standard-2xCheck ps to see the new process type running, for example:$ heroku ps=== web: `bundle exec rails server -p $PORT`web.1: up for 2m=== worker: `env QUEUE=* bundle exec rake resque:work`worker.1: up for 5sUse heroku logs --ps worker to view just the messages from the worker process type:$ heroku logs --ps worker2011-04-25T18:33:25-07:00 heroku[worker.1]: State changed from created to starting2011-04-26T01:33:26+00:00 heroku[worker.1]: Running process with command: `env QUEUE=* bundle exec rake resque:work`2011-04-25T18:33:29-07:00 heroku[worker.1]: State changed from starting to up2011-04-26T01:33:29+00:00 app[worker.1]: (in /app)The output we see here matches our local output, interleaved with system messages from Heroku’s system components such as the router and dyno manager.You can scale up higher with the same command. For example, two web dynos and four worker dynos:$ heroku ps:scale web=2 worker=4Scaling web processes... done, now running 2Scaling worker processes... done, now running 4$ heroku ps=== web: `bundle exec rails server -p $PORT`web.1: up for 7mweb.2: up for 2s=== worker: `env QUEUE=* bundle exec rake resque:work`worker.1: up for 7mworker.2: up for 3sworker.3: up for 2sworker.4: up for 3sRead more about scaling.More process type examplesThe Procfile model of running processes types is extremely flexible. You can run any number of dynos with whatever arbitrary commands you want, and scale each independently.For example, using Ruby you could run two types of queue workers, each consuming different queues, as well as a release phase command:release: ./release-tasks.shworker: env QUEUE=* bundle exec rake resque:workurgentworker: env QUEUE=urgent bundle exec rake resque:workThese can then be
2025-04-11IntroductionWeb workers are a powerful feature in modern browsers that allow JavaScript to spawn background threads and perform resource-intensive tasks asynchronously without blocking the main UI thread. This helps ensure smooth and responsive user experiences. In this comprehensive guide, we will cover the following topics:What are web workers and why are they useful?A practical example to demonstrate web workers Communicating between web workers and main UI threadBrowser support and fallback optionsPerformance considerations and best practicesCommon use cases for web workersBy the end, you‘ll have a solid understanding of how to leverage web workers to build high-performance web apps. Let‘s get started!What are Web Workers?Web workers provide a simple mechanism to run scripts in background threads separate from the main execution thread. Some key aspects:They allow long-running computations and I/O intensive operations without blocking the UIWeb workers run in another global context, don‘t have access to the DOMThey communicate with the main thread via message passing Created using new Worker() or new SharedWorker()Conceptually, you can think of web workers as a way to delegate heavy tasks to other threads running in parallel. The key advantage is the UI never gets blocked.For example, if you need to parse a huge local CSV dataset, that could lock up the browser for several seconds. With web workers, you can spin up a background thread to handle the parsing without impacting UI responsiveness.Diagram showing how web workers run on separate threads.Now that we know what web workers are, let‘s look at a practical example to see them in action.To demonstrate web workers, we will build a basic web app that fetches cryptocurrency prices every few seconds and displays them in a chart. Without workers, this would quickly become unusable as the main UI thread gets blocked each time we refresh the prices.Here is an overview of the app:Main UI thread with controls and chart Web worker thread that polls prices and sends messages Communication between the threads via postMessage()App Structure/- index.html- style.css- app.js|— /js - worker.js The key files are:app.js: Main application logic for UIworker.js: Web worker thread code Creating a Dedicated Web WorkerFirst, we need to spin up a web worker from the main app using the Worker constructor:// Create new workerconst worker = new Worker(‘./js/worker.js‘);This spawns a background thread and executes worker.js in a separate global context. Inside worker.js we can register handlers to receive and respond to messages:// Listen for messages from main threadself.addEventListener(‘message‘, (e) => { // .. worker logic here // Post back result self.postMessage(result);});For this app, the worker will poll new price data every few seconds and post messages back to the main thread.Main Thread LogicWith the worker setup, the main script app.js will have UI handlers to start/stop polling prices, render the chart, and process incoming messages:// Listen for messages from workerworker.addEventListener(‘message‘, (e) => { // Update chart with new prices updateChart(e.data); });// Handler to start polling prices startPollingBtn.addEventListener(‘click‘, () => { // Post message to start worker worker.postMessage({‘cmd‘: ‘start‘});});Here we listen for messages from the worker and
2025-04-05Use the posted data to update the chart.The full main thread code is available in this CodePen.Web Worker ThreadNow inside worker.js we can poll the prices and post messages back to main thread:// CoinDesk BPI endpointconst apiUrl = ‘ Initialize prices let prices = {}; // Poll prices setInterval(async () => { // Fetch latest data const res = await fetch(apiUrl); prices = await res.json(); // Post back to main thread self.postMessage(prices);}, 3000); // 3sec intervalWe use setInterval to poll the API every few seconds, then post the updated prices back to the main thread.The full worker script code is available here.And that‘s it! Together the main thread and worker script coordinate to fetch data and update the UI without blocking.Here is a CodePen showing the full demo: See the Pen Web Worker Demo: Fetching API Data by Aravind (@aravindballa) on CodePen.Hopefully this gives a real-world example of leveraging web workers! 😊Communicating Between ThreadsAs seen above, the primary way for web workers to communicate with the main thread is by posting messages to each other.The main interface for this in both contexts is the postMessage() method. Along with the message content, you can specify message origins and transferrable objects.Some key mechanisms for thread communication:Main Thread -> Workerworker.postMessage(): Send message to worker worker.onmessage: Listen for messages from workerWorker Thread -> Main Thread self.postMessage(): Post messages back to main threadself.onmessage: Listen for messages from main threadAdditionally, web workers expose mechanisms like terminate() to end threads and handle errors.This abstracted message-passing approach allows you to coordinate between threads without worrying about low-level concurrency issues.Browser SupportMost major browsers have excellent support for web workers:However, some limitations exist:IE10 and below do not support web workers at all Safari support is more recent For cases when web workers are not supported, you can fallback to using Web Worker polyfills. Some popular options:WorkerizeWeb Worker ThreadsThese polyfills emulate worker threads by spawned separate processes. This ensures backwards capability while limiting concurrency.Performance ConsiderationsWhile web workers are quite useful, some care should be taken to use them efficiently: Memory overheads – Each worker has its own global context, so memory usage can add upThread contention – Creating too many workers could contend for limited browser threads Message passing costs – Serializing excessive large data back-and-forth has a costSome best practices include:Keep the number of active web workers reasonable (under 10)Pool/reuse workers instead of continuously creating new ones Pass small message data instead of entire huge objectsUse Comlink for optimized message passing Additionally, you should not use web workers for any browser-specific APIs like DOM manipulation, as they are not exposed to worker contexts.Common Use CasesHere are some common examples where web workers shine:Processing large local datasets (JSON, CSV, etc) Polling and streaming external APIsRunning expensive computations like image filters Periodic background syncs with serverPrefetching assets/data for later use Parsing multimedia files (audio, video, images)Spellchecking/grammar validation Essentially any CPU or I/O intensive tasks that could block the main UI thread are good fits for delegation to a web worker.ConclusionI hope this
2025-03-24CentreStackInstallationGuideBuild6.5.2033.325526/1/2015________________________________________________________________________Table of ContentsOverview of CentreStackDeployment DiagramStep 1: Prepare the File StorageStep 2: Prepare the Active Directory(Optional)Step 3: Prepare the Database ServerStep 4: Prepare the Worker NodesStep 5: Start InstallationStep 6: Initial ConfigurationStep 7: Check Out Web PortalStep 8: Check out the ManagementConsoleStep 9: Enable SSL – Install SSLCertificateStep 10: Set up Worker NodepropertiesStep 11: Verify External URL,Internal URL and Node NameVerify External URLVerify Internal URLVerify Node NameStep 12: Add the node to the LoadBalancerStep 13: Setup the Second Node(Worker Node #2)Option 1 – GUI SetupOption 2 – Command Line Script Setup13.1 – Preparation on the Worker Node#113.2 - Clone Program Files13.3 – Clone the Registry13.4 – Command Line Setup for the IISASP.NET and WCF applications.13.5 - Import SSL Certificate13.6 - Sanity Check Worker Node #213.7 – Add the worker node 2 to thecluster13.8 – Add the worker node #2 to theLoad Balancer.13.9 Pre-Compile ASP.NET PagesStep 14: Setup Worker Node #3BrandingSelf-Service BrandingFull-Branding ServiceUpgradeOption #1 – GUI Installer for UpgradeOption #2 – Command Line UpgradeStep 1 – Unzip the FolderStep 2 – Copy files over to theProgram Files. Overview of CentreStackCentreStackprovides value-added services on top of cloud storage services or local storageservices. Cloud Storage services include those from OpenStack Swift, Amazon S3and its compatibles, Google Cloud Storage, HP Cloud Storage and many others. LocalStorage Services include file server Storage, SAN or NAS storage. CentreStackvalue-added services can be summarized as Backup, Access,Sync and Share, Identity, Control andCollaboration (BASIC). The value-added services are also known asEnterprise File Sync and Share services (EFSS).CentreStack isa cluster of web services built on top of the Microsoft Web Platform. Itprovides the BASIC value-added services that facilitate onlinestorage access for PCs, Macs, File Servers, Web Browsers, and Mobile Devices.The servicescan be deployed in flexible combinations to meet different needs. For example,you can deploy it on premise as a private cloud or you can deploy itoff-premise in a data center, managed by your managed service provider (MSP) oryou can deploy it in Amazon EC2-like environment as virtual-private deployment.There are threedifferent types of machines (or Virtual Machines). In the smallest deploymentunit, the three different logical nodes can co-exist in one single
2025-03-24Worker was registered on this origin,there's still a message saying there is no current service worker.That's because this page is not within the registered service worker's scope.Scope limits what pages the service worker controls.In this example, that means the service worker loaded from /subdir/sw.js can only control pages located in /subdir/ or its subtree.The above is how scoping works by default,but the maximum allowed scope can be overridden by setting theService-Worker-Allowed response header,as well as passing ascope option to the register method.Unless there's a very good reason to limit service worker scope to a subset of an origin,load a service worker from the root directory of the web server so that its scope is as broad as possible,and don't worry about the Service-Worker-Allowed header. It's a lot simpler for everyone that way.ClientWhen it's said that a service worker is controlling a page, it's really controlling a client.A client is any open page whose URL falls within the scope of that service worker.Specifically, these are instances of a WindowClient.The lifecycle of a new service workerIn order for a service worker to control a page,it must first be brought into existence, so to speak.Let's begin with what happens when a brand new service worker is deployed for a website with no active service worker.RegistrationRegistration is the initial step of the service worker lifecycle: // Don't register the service worker // until the page has fully loaded window.addEventListener('load', () => { // Is service worker available? if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').then(() =>
2025-04-05Physics simulation return data * 2; // Example calculation}Invoke the Worker from the Main Thread: In your main WebGL script, you can invoke the Web Worker and pass data to it.const worker = new Worker('worker.js');worker.postMessage(100); // Send data to the workerworker.onmessage = function(event) { const result = event.data; console.log('Result from worker:', result);};By using Web Workers, you can offload complex computations and keep your WebGL application responsive, even when performing heavy calculations.11. Monitor and Debug WebGL PerformanceOptimization doesn’t stop once your application is built. Continuous monitoring and debugging are essential to ensure that your WebGL project maintains high performance, especially as you add new features or assets. Several tools and techniques can help you monitor performance in real-time and identify potential bottlenecks.WebGL Debugging Tools:Chrome DevTools: The Performance panel in Chrome DevTools allows you to capture and analyze frame rates, memory usage, and CPU/GPU activity. You can see how long each frame takes to render and identify potential issues such as high draw calls or inefficient shaders.Firefox Performance Tools: Firefox offers similar tools to profile WebGL applications, allowing you to track frame rates, memory usage, and WebGL draw calls.Three.js Inspector: If you’re working with Three.js, the Three.js Inspector Chrome extension is a valuable tool for debugging your scene. It lets you visualize the scene graph, inspect materials and shaders, and monitor performance metrics specific to your Three.js project.Profiling and Identifying Bottlenecks:When using these tools, focus on key performance metrics such as:Frame Rate: The ideal frame rate is 60 FPS for smooth interactions,
2025-04-12