Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/useWebWorkerFn.md
1---2category: Browser3---45# useWebWorkerFn67Run expensive functions without blocking the UI, using a simple syntax that makes use of Promise. A port of [alewin/useWorker](https://github.com/alewin/useWorker).89## Usage1011### Basic example1213```ts14import { useWebWorkerFn } from '@vueuse/core'1516const { workerFn } = useWebWorkerFn(() => {17// some heavy works to do in web worker18})19```2021### With dependencies2223```ts {7-9}24import { useWebWorkerFn } from '@vueuse/core'2526const { workerFn, workerStatus, workerTerminate } = useWebWorkerFn(27dates => dates.sort(dateFns.compareAsc),28{29timeout: 50000,30dependencies: [31'https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js', // dateFns32],33},34)35```3637### With local dependencies3839```ts {9-9}40import { useWebWorkerFn } from '@vueuse/core'4142const pow = (a: number) => a * a4344const { workerFn, workerStatus, workerTerminate } = useWebWorkerFn(45numbers => pow(numbers),46{47timeout: 50000,48localDependencies: [pow]49},50)51```5253## Web Worker5455Before you start using this function, we suggest you read the [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) documentation.5657## Credit5859This function is a Vue port of https://github.com/alewin/useWorker by Alessio Koci, with the help of [@Donskelle](https://github.com/Donskelle) to migration.6061## Type Declarations6263```ts64export type WebWorkerStatus =65| "PENDING"66| "SUCCESS"67| "RUNNING"68| "ERROR"69| "TIMEOUT_EXPIRED"70export interface UseWebWorkerOptions extends ConfigurableWindow {71/**72* Number of milliseconds before killing the worker73*74* @default undefined75*/76timeout?: number77/**78* An array that contains the external dependencies needed to run the worker79*/80dependencies?: string[]81/**82* An array that contains the local dependencies needed to run the worker83*/84localDependencies?: Function[]85}86export interface UseWebWorkerFnReturn<T extends (...fnArgs: any[]) => any> {87workerFn: (...fnArgs: Parameters<T>) => Promise<ReturnType<T>>88workerStatus: ShallowRef<WebWorkerStatus>89workerTerminate: (status?: WebWorkerStatus) => void90}91/**92* Run expensive function without blocking the UI, using a simple syntax that makes use of Promise.93*94* @see https://vueuse.org/useWebWorkerFn95* @param fn96* @param options97*/98export declare function useWebWorkerFn<T extends (...fnArgs: any[]) => any>(99fn: T,100options?: UseWebWorkerOptions,101): UseWebWorkerFnReturn<T>102```103