### Run Example Start Script Source: https://github.com/tanstack/pacer/blob/main/CONTRIBUTING.md To run examples, navigate into the example directory and start the dev server. Do NOT install dependencies again or do any linking, as Nx handles this. ```bash pnpm start ``` -------------------------------- ### Install and Run Example Source: https://github.com/tanstack/pacer/blob/main/examples/react/useQueuerWithPersister/README.md Install dependencies and run the development server to see the example in action. ```bash npm install npm run dev ``` -------------------------------- ### Run TanStack Pacer Example Source: https://github.com/tanstack/pacer/blob/main/examples/react/util-comparison/README.md Starts the development server for the TanStack Pacer utilities example. This command is used after installing dependencies. ```bash npm run dev ``` -------------------------------- ### Example Usage Source: https://github.com/tanstack/pacer/blob/main/docs/reference/classes/AsyncDebouncer.md Demonstrates how to create and use the AsyncDebouncer with an example API call. ```APIDOC ## Example ```ts const asyncDebouncer = new AsyncDebouncer(async (value: string) => { const results = await searchAPI(value); return results; // Return value is preserved }, { wait: 500, onError: (error) => { console.error('Search failed:', error); } }); // Called on each keystroke but only executes after 500ms of no typing // Returns the API response directly const results = await asyncDebouncer.maybeExecute(inputElement.value); ``` ``` -------------------------------- ### start() Source: https://github.com/tanstack/pacer/blob/main/docs/reference/classes/Queuer.md Starts processing items in the queue. If already isRunning, does nothing. ```APIDOC ## start() ### Description Starts the queue processing. If the queue is already running, this method has no effect. ### Method POST (conceptual, as this is a library function) ### Endpoint N/A (Library function) ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **void** - This method does not return a value. #### Response Example ```json null ``` ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/tanstack/pacer/blob/main/CONTRIBUTING.md Ensure you have pnpm installed. Then, install project dependencies and linkages by running this command from the project root. ```bash pnpm install ``` -------------------------------- ### Install TanStack Pacer Dependencies Source: https://github.com/tanstack/pacer/blob/main/examples/react/util-comparison/README.md Installs the necessary dependencies for running the TanStack Pacer example. Use this command in your project's root directory. ```bash npm install ``` -------------------------------- ### Starting Automatic Queue Processing Source: https://github.com/tanstack/pacer/blob/main/docs/framework/preact/reference/functions/useQueuedState.md Demonstrates how to manually start the automatic processing of items in the queue using the `start` method on the queue object. ```tsx // Start automatic processing const startProcessing = () => { queue.start(); }; ``` -------------------------------- ### AsyncBatcher Example Usage Source: https://github.com/tanstack/pacer/blob/main/docs/reference/classes/AsyncBatcher.md A practical example demonstrating how to create and use the AsyncBatcher to process items. ```APIDOC ## Example Usage ```ts const batcher = new AsyncBatcher( async (items) => { const result = await processItems(items); console.log('Processing batch:', items); return result; }, { maxSize: 5, wait: 2000, onSuccess: (result) => console.log('Batch succeeded:', result), onError: (error) => console.error('Batch failed:', error) } ); batcher.addItem(1); batcher.addItem(2); // Batches are processed automatically after 2 seconds or when 5 items are added. // You can also manually trigger execution with batcher.execute() ``` ``` -------------------------------- ### Start Development Server Source: https://github.com/tanstack/pacer/blob/main/examples/angular/asyncDebounce/README.md Run this command to start a local development server. The application will auto-reload on source file changes. ```bash ng serve ``` -------------------------------- ### Add Items and Start Processing Source: https://github.com/tanstack/pacer/blob/main/docs/framework/solid/reference/functions/createAsyncQueuer.md Demonstrates how to add new items to the queue and start the processing of queued items. ```tsx // Add items to queue asyncQueuer.addItem(newItem); // Start processing asyncQueuer.start(); ``` -------------------------------- ### Example Usage Source: https://github.com/tanstack/pacer/blob/main/docs/reference/classes/Queuer.md Illustrates how to create and use the Queuer class with different configurations. ```APIDOC ## Example Usage ### Auto-processing queue with wait time ```ts const autoQueue = new Queuer((n) => console.log(n), { started: true, // Begin processing immediately wait: 1000, // Wait 1s between items onExecute: (item, queuer) => console.log(`Processed ${item}`) }); autoQueue.addItem(1); // Will process after 1s autoQueue.addItem(2); // Will process 1s after first item ``` ### Manual processing queue ```ts const manualQueue = new Queuer((n) => console.log(n), { started: false }); manualQueue.addItem(1); // [1] manualQueue.addItem(2); // [1, 2] manualQueue.execute(); // logs 1, queue is [2] manualQueue.getNextItem(); // returns 2, queue is empty ``` ``` -------------------------------- ### asyncQueue() - Usage Example Source: https://github.com/tanstack/pacer/blob/main/docs/reference/functions/asyncQueue.md A practical example demonstrating how to use the asyncQueue function to create a queue and enqueue tasks. ```APIDOC ## Example ```ts const enqueue = asyncQueue(async (item) => { return item.toUpperCase(); }, { concurrency: 2, wait: 100, onSuccess: (result) => console.log('Processed:', result) }); enqueue('hello'); ``` ``` -------------------------------- ### Complete Async Batcher Example with Callbacks Source: https://github.com/tanstack/pacer/blob/main/docs/framework/preact/reference/functions/useAsyncBatcher.md A comprehensive example demonstrating the async batcher with both onSuccess and onError callbacks for detailed event handling. ```tsx const asyncBatcher = useAsyncBatcher( async (items) => { const results = await Promise.all(items.map(item => processItem(item))); return results; }, { maxSize: 10, wait: 2000, onSuccess: (result) => { console.log('Batch processed successfully:', result); }, onError: (error) => { console.error('Batch processing failed:', error); } } ); ``` -------------------------------- ### Start Development Server Source: https://github.com/tanstack/pacer/blob/main/CONTRIBUTING.md Auto-build and auto-test files as you edit by running this command from the project root. ```bash pnpm dev ``` -------------------------------- ### Async Queuer - Example Usage Source: https://github.com/tanstack/pacer/blob/main/docs/framework/solid/reference/functions/createAsyncQueuer.md Provides various examples of how to use the `createAsyncQueuer` function, including default behavior, opting into tracking queue state changes, and opting into tracking processing metrics. ```APIDOC ## Example Usage ```tsx // Default behavior - no reactive state subscriptions const asyncQueuer = createAsyncQueuer(async (item) => { // process item return await fetchData(item); }, { initialItems: [], concurrency: 2, maxSize: 100, started: false, onSuccess: (result) => { console.log('Item processed:', result); }, onError: (error) => { console.error('Processing failed:', error); } }); // Opt-in to track queue state changes (optimized for UI updates) const asyncQueuer = createAsyncQueuer( async (item) => await fetchData(item), { concurrency: 2, started: true }, (state) => ({ pendingItems: state.pendingItems, activeItems: state.activeItems, isRunning: state.isRunning }) ); // Opt-in to track processing metrics changes (optimized for tracking progress) const asyncQueuer = createAsyncQueuer( async (item) => await fetchData(item), { concurrency: 2, started: true }, (state) => ({ successCount: state.successCount, errorCount: state.errorCount, settleCount: state.settleCount }) ); // Add items to queue asyncQueuer.addItem(newItem); // Start processing asyncQueuer.start(); // Access the selected state (will be empty object {} unless selector provided) const { pendingItems, activeItems } = asyncQueuer.state(); ``` ``` -------------------------------- ### Install TanStack Pacer React Adapter Source: https://github.com/tanstack/pacer/blob/main/docs/framework/react/adapter.md Install the React Adapter package using npm. ```sh npm install @tanstack/react-pacer ``` -------------------------------- ### Batcher Example Usage Source: https://github.com/tanstack/pacer/blob/main/docs/reference/classes/Batcher.md Demonstrates how to create and use the Batcher class. ```APIDOC ## Example ```ts const batcher = new Batcher( (items) => console.log('Processing batch:', items), { maxSize: 5, wait: 2000, onExecute: (batch, batcher) => console.log('Batch executed:', batch) } ); batcher.addItem(1); batcher.addItem(2); // After 2 seconds or when 5 items are added, whichever comes first, // the batch will be processed // batcher.flush() // manually trigger a batch ``` ``` -------------------------------- ### Install TanStack Pacer Preact Adapter Source: https://github.com/tanstack/pacer/blob/main/docs/framework/preact/adapter.md Install the Preact Adapter package using npm. ```sh npm install @tanstack/preact-pacer ``` -------------------------------- ### Queuer Example for File Uploads Source: https://github.com/tanstack/pacer/blob/main/docs/framework/preact/adapter.md Utilize `useQueuer` to manage concurrent file uploads. This example demonstrates adding multiple files to a queue with a specified concurrency limit. ```tsx import { useQueuer } from '@tanstack/preact-pacer' function UploadComponent() { const queuer = useQueuer( async (file: File) => { await uploadFile(file) }, { concurrency: 3 } ) const handleFileSelect = (files: FileList) => { Array.from(files).forEach((file) => { queuer.addItem(file) }) } return ( { if (e.target.files) { handleFileSelect(e.target.files) } }} /> ) } ``` -------------------------------- ### Install TanStack Pacer Solid Adapter Source: https://github.com/tanstack/pacer/blob/main/docs/framework/solid/adapter.md Install the Solid Adapter for TanStack Pacer using npm. ```sh npm install @tanstack/solid-pacer ``` -------------------------------- ### Pre-populate Queue with Initial Items Source: https://github.com/tanstack/pacer/blob/main/docs/guides/queuing.md Initialize the queue with a list of items and optionally start processing immediately by setting `started: true`. ```typescript const queue = new Queuer( (item) => { // Process each item console.log('Processing:', item) }, { initialItems: [1, 2, 3], started: true // Start processing immediately } ) ``` -------------------------------- ### start() Source: https://github.com/tanstack/pacer/blob/main/docs/reference/classes/AsyncQueuer.md Initiates the processing of items within the queue. If the queue is already processing, this method has no effect. ```APIDOC ## start() ### Description Starts processing items in the queue. If already running, does nothing. ### Method POST (assumed, as it initiates an action) ### Endpoint Not applicable (method on an object instance) ### Response #### Success Response (200) - **void** - Indicates the start operation was successful. ``` -------------------------------- ### Starting Queue Processing Source: https://github.com/tanstack/pacer/blob/main/docs/framework/preact/reference/functions/useAsyncQueuedState.md Start the processing of items in the queue using the asyncQueuer.start() method. ```tsx asyncQueuer.start(); ``` -------------------------------- ### Install TanStack Pacer Packages Source: https://context7.com/tanstack/pacer/llms.txt Install the appropriate TanStack Pacer package based on your framework or for vanilla JavaScript. ```bash # React npm install @tanstack/react-pacer ``` ```bash # Solid npm install @tanstack/solid-pacer ``` ```bash # Angular npm install @tanstack/angular-pacer ``` ```bash # Preact npm install @tanstack/preact-pacer ``` ```bash # Vanilla JavaScript (no framework) npm install @tanstack/pacer ``` -------------------------------- ### Install Solid Devtools Adapter and Plugin Source: https://github.com/tanstack/pacer/blob/main/docs/installation.md Install the Solid devtools adapter and Pacer devtools plugin as dev dependencies to inspect and monitor your pacers in Solid applications. ```bash npm install --save-dev @tanstack/solid-devtools @tanstack/solid-pacer-devtools ``` -------------------------------- ### Install Solid Pacer Devtools Source: https://github.com/tanstack/pacer/blob/main/docs/devtools.md Install the necessary packages for Solid Pacer devtools. These are separate from the core Solid devtools. ```sh npm install @tanstack/solid-devtools @tanstack/solid-pacer-devtools ``` -------------------------------- ### Install Core Pacer Package Source: https://github.com/tanstack/pacer/blob/main/docs/installation.md Install the core TanStack Pacer package directly if you are not using a specific framework adapter. ```bash npm install @tanstack/pacer ``` -------------------------------- ### AsyncThrottler Example Usage Source: https://github.com/tanstack/pacer/blob/main/docs/reference/classes/AsyncThrottler.md Demonstrates how to create and use an AsyncThrottler instance. ```APIDOC ## Example ```ts const throttler = new AsyncThrottler(async (value: string) => { const result = await saveToAPI(value); return result; // Return value is preserved }, { wait: 1000, onError: (error) => { console.error('API call failed:', error); } }); // Will only execute once per second no matter how often called // Returns the API response directly const result = await throttler.maybeExecute(inputElement.value); ``` ``` -------------------------------- ### Inject Async Queuer Example Source: https://github.com/tanstack/pacer/blob/main/examples/angular/injectAsyncQueuer/src/app/app.html This example demonstrates adding jobs quickly to a queuer with concurrency set to 2, wait time to 200ms, and a maximum size of 5. It shows how to manage job states (pending, active, results) and the overall queuer state. ```typescript import { injectAsyncQueuer } from "@tanstack/pacer" const queuer = injectAsyncQueuer({ id: "my-queuer", concurrency: 2, wait: 200, maxSize: 5 }) // Add jobs quickly to see queuing queuer.add(Array.from({ length: 10 }, (_, i) => ({ text: `Job ${i + 1}` }))) // Add jobs one by one queuer.add({ text: "Another Job" }) // Start the queuer queuer.start() // Stop the queuer queuer.stop() // Clear all pending and active jobs queuer.clear() // Flush all pending jobs immediately queuer.flush() // Reset the queuer to its initial state queuer.reset() // Get the current state of the queuer console.log(queuer.state()) // Get the results of completed jobs console.log(queuer.results()) // Get the last added job console.log(queuer.lastAdd()) // Example of a job function async function myJobFunction(job) { console.log(`Starting job: ${job.text}`) await new Promise(resolve => setTimeout(resolve, 1000)) console.log(`Finished job: ${job.text}`) return `Result for ${job.text}` } // Add a job with a custom function queuer.add({ text: "Custom Job", handler: myJobFunction }) ``` -------------------------------- ### Rate Limiter Example for API Calls Source: https://github.com/tanstack/pacer/blob/main/docs/framework/preact/adapter.md Implement rate limiting for API requests using `useRateLimiter`. This example shows how to set limits, window duration, window type, and handle rejected requests. ```tsx import { useRateLimiter } from '@tanstack/preact-pacer' function ApiComponent() { const rateLimiter = useRateLimiter( (data: string) => { return fetch('/api/endpoint', { method: 'POST', body: JSON.stringify({ data }), }) }, { limit: 5, window: 60000, windowType: 'sliding', onReject: () => { alert('Rate limit reached. Please try again later.') }, } ) const handleSubmit = () => { const remaining = rateLimiter.getRemainingInWindow() if (remaining > 0) { rateLimiter.maybeExecute('some data') } } return } ``` -------------------------------- ### Basic Throttling Example Source: https://github.com/tanstack/pacer/blob/main/docs/reference/functions/throttle.md Illustrates basic throttling where a function can execute at most once per second. ```typescript // Basic throttling - max once per second const throttled = throttle(updateUI, { wait: 1000 }); ``` -------------------------------- ### Controlling Queue Processing Source: https://github.com/tanstack/pacer/blob/main/docs/framework/preact/reference/functions/useQueuedValue.md Examples of controlling the queue processing using the `stop` and `start` methods on the queuer instance. ```tsx // Control the queue const pauseProcessing = () => { queuer.stop(); }; const resumeProcessing = () => { queuer.start(); }; ``` -------------------------------- ### Get Default Pacer Options Source: https://github.com/tanstack/pacer/blob/main/docs/framework/react/reference/functions/useDefaultPacerOptions.md Use this function to retrieve the default options for the PacerProvider. No setup or imports are required beyond the function itself. ```typescript function useDefaultPacerOptions(): PacerProviderOptions; ``` -------------------------------- ### Dynamically Update Queue Configuration Source: https://github.com/tanstack/pacer/blob/main/docs/guides/queuing.md Modify queue options after creation using `setOptions()`. This example shows changing the `wait` time and starting the queue. ```typescript const queue = new Queuer( (item) => { // Process each item console.log('Processing:', item) }, { wait: 1000, started: false } ) // Change configuration queue.setOptions({ wait: 500, // Process items twice as fast started: true // Start processing }) ``` -------------------------------- ### Create and Use a Throttled Signal Source: https://github.com/tanstack/pacer/blob/main/docs/framework/angular/reference/functions/injectThrottledSignal.md Example of creating a throttled signal for scroll position, getting its value, updating it, and accessing the throttler's state. ```typescript const throttledScrollY = injectThrottledSignal(0, { wait: 100 }) // Get value console.log(throttledScrollY()) // Set/update value (throttled) throttledScrollY.set(window.scrollY) // Access throttler console.log(throttledScrollY.throttler.state().isPending) ``` -------------------------------- ### queue() - Example Usage Source: https://github.com/tanstack/pacer/blob/main/docs/reference/functions/queue.md Demonstrates how to use the queue function for basic sequential processing and priority queue scenarios. ```APIDOC ### Example Usage ```ts // Basic sequential processing const processItems = queue((n) => console.log(n), { wait: 1000, onItemsChange: (queuer) => console.log(queuer.peekAllItems()) }); processItems(1); // Logs: 1 processItems(2); // Logs: 2 after 1 completes // Priority queue const processPriority = queue((n) => console.log(n), { getPriority: n => n // Higher numbers processed first }); processPriority(1); processPriority(3); // Processed before 1 ``` ``` -------------------------------- ### Default useQueuedValue Behavior Source: https://github.com/tanstack/pacer/blob/main/docs/framework/preact/reference/functions/useQueuedValue.md Example of using useQueuedValue with default settings, resulting in no reactive state subscriptions. Configure 'wait' for delays and 'started' to begin processing immediately. ```tsx // Default behavior - no reactive state subscriptions const [value, queuer] = useQueuedValue(initialValue, { wait: 500, // Wait 500ms between processing each change started: true // Start processing immediately }); ``` -------------------------------- ### Access Debouncer State Signals Source: https://github.com/tanstack/pacer/blob/main/docs/framework/solid/reference/functions/createDebouncedSignal.md This example demonstrates how to access the debouncer's state properties as signals. These signals can be read directly to get the current state of the debouncer. ```tsx console.log('Executions:', debouncer.state().executionCount); console.log('Is pending:', debouncer.state().isPending); ``` -------------------------------- ### Injecting AsyncQueuer with default behavior Source: https://github.com/tanstack/pacer/blob/main/docs/framework/angular/reference/functions/injectAsyncQueuer.md This example demonstrates the default behavior of injectAsyncQueuer, which does not include reactive state subscriptions. You must opt-in to state tracking by providing a selector function. This setup is useful for integrating with any state management solution. ```typescript const queuer = injectAsyncQueuer( async (item: Data) => { const response = await fetch('/api/process', { method: 'POST', body: JSON.stringify(item) }); return response.json(); }, { concurrency: 2, wait: 1000 } ); // Add items queuer.addItem(data1); queuer.addItem(data2); // Access the selected state const { items, isExecuting } = queuer.state(); ``` -------------------------------- ### Batching up to 5 items or flushing after 1 second Source: https://github.com/tanstack/pacer/blob/main/examples/angular/injectAsyncBatchedCallback/src/app/app.html This example demonstrates how to use injectAsyncBatchedCallback to queue items. The callback will process items in batches, either when a batch reaches 5 items or after 1 second has passed, whichever comes first. No specific setup or imports are shown, but it implies the existence of queuedCount(), isProcessing(), and processedBatches variables. ```typescript @if (processedBatches.length === 0) { No batches processed yet. Click "Enqueue" a few times. } @else { @for (batch of processedBatches; track $index) { {{ batch.timestamp }} ({{ batch.items.length }} items) {{ batch.items.join(', ') }} } } ``` -------------------------------- ### Basic Async Batcher Setup Source: https://github.com/tanstack/pacer/blob/main/docs/framework/preact/reference/functions/useAsyncBatcher.md Initialize an async batcher for API requests without reactive state subscriptions. Configure batch size and wait time. ```tsx const asyncBatcher = useAsyncBatcher( async (items) => { const results = await Promise.all(items.map(item => processItem(item))); return results; }, { maxSize: 10, wait: 2000 } ); ``` -------------------------------- ### Control Queue Processing with Start and Stop Source: https://github.com/tanstack/pacer/blob/main/docs/guides/queuing.md Initialize a queue in a paused state using `started: false` and control processing manually with `start()` and `stop()`. Items can also be processed manually using `getNextItem()`. ```typescript const queue = new Queuer( (item) => { // Process each item console.log('Processing:', item) }, { started: false // Start paused } ) queue.start() // Begin processing items queue.stop() // Pause processing // Manually process items while the queue is stopped (run it your own way) queue.getNextItem() // Get next item queue.getNextItem() // Get next item queue.getNextItem() // Get next item ``` -------------------------------- ### Async Batcher Configuration and Usage Source: https://github.com/tanstack/pacer/blob/main/docs/framework/solid/reference/functions/createAsyncBatcher.md Demonstrates how to create and use the Async Batcher with various configuration options, including custom unmount behavior, success/error callbacks, and state selectors. ```APIDOC ## createAsyncBatcher ### Description Creates an asynchronous batcher utility to process batched operations efficiently. ### Parameters #### fn - **Type**: (`items`) => `Promise` - **Description**: The asynchronous function that processes the batched items. #### options - **Type**: [`SolidAsyncBatcherOptions`](../interfaces/SolidAsyncBatcherOptions.md) - **Description**: Configuration options for the batcher, including `maxSize`, `wait`, `onUnmount`, `onSuccess`, and `onError`. #### selector (Optional) - **Type**: (`state`) => `TSelected` - **Description**: A function to select specific parts of the batcher's state for optimized updates. ### Returns - **Type**: [`SolidAsyncBatcher`](../interfaces/SolidAsyncBatcher.md) - **Description**: An instance of the Async Batcher with methods to manage and interact with the batching process. ### Example: Custom Unmount Behavior ```tsx const batcher = createAsyncBatcher(fn, { maxSize: 10, wait: 2000, onUnmount: (b) => b.flush() }); ``` ### Example: Default Behavior ```tsx const asyncBatcher = createAsyncBatcher( async (items) => { const results = await Promise.all(items.map(item => processItem(item))); return results; }, { maxSize: 10, wait: 2000, onSuccess: (result) => { console.log('Batch processed successfully:', result); }, onError: (error) => { console.error('Batch processing failed:', error); } } ); ``` ### Example: State Selection (UI Updates) ```tsx const asyncBatcher = createAsyncBatcher( async (items) => { const results = await Promise.all(items.map(item => processItem(item))); return results; }, { maxSize: 10, wait: 2000 }, (state) => ({ items: state.items, isExecuting: state.isExecuting }) ); ``` ### Example: State Selection (Error Handling) ```tsx const asyncBatcher = createAsyncBatcher( async (items) => { const results = await Promise.all(items.map(item => processItem(item))); return results; }, { maxSize: 10, wait: 2000 }, (state) => ({ hasError: state.hasError, lastError: state.lastError }) ); ``` ### Methods #### addItem - **Description**: Adds an item to the batch. - **Usage**: `asyncBatcher.addItem(newItem);` #### execute - **Description**: Manually executes the current batch. - **Usage**: `const result = await asyncBatcher.execute();` #### state - **Description**: Accesses the selected state of the batcher. - **Usage**: `const { items, isExecuting } = asyncBatcher.state();` ### Unmount Behavior By default, the primitive cancels any pending batch and aborts any in-flight execution when the owning component unmounts. Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them. Use the `onUnmount` option to customize this behavior. ``` -------------------------------- ### createBatcher Usage Examples Source: https://github.com/tanstack/pacer/blob/main/docs/framework/solid/reference/functions/createBatcher.md Illustrates various ways to use the createBatcher function, including default behavior, state selection, and unmount customization. ```APIDOC ## Example Usage ### Default Behavior (No Reactive State Subscriptions) ```tsx const batcher = createBatcher( (items) => { // Process batch of items console.log('Processing batch:', items); }, { maxSize: 5, wait: 2000, onExecute: (batcher) => console.log('Batch executed'), getShouldExecute: (items) => items.length >= 3 } ); ``` ### Opt-in to Track Items or isRunning Changes ```tsx const batcher = createBatcher( (items) => console.log('Processing batch:', items), { maxSize: 5, wait: 2000 }, (state) => ({ items: state.items, isRunning: state.isRunning }) ); ``` ### Opt-in to Track Execution Metrics Changes ```tsx const batcher = createBatcher( (items) => console.log('Processing batch:', items), { maxSize: 5, wait: 2000 }, (state) => ({ executionCount: state.executionCount, totalItemsProcessed: state.totalItemsProcessed }) ); ``` ### Adding Items and Controlling the Batcher ```tsx // Add items to batch batcher.addItem('task1'); batcher.addItem('task2'); // Control the batcher batcher.stop(); // Pause processing batcher.start(); // Resume processing // Access the selected state const { items, isRunning } = batcher.state(); ``` ### Unmount Behavior Customization ```tsx const batcher = createBatcher(fn, { maxSize: 10, wait: 2000, onUnmount: (b) => b.flush() }); ``` ``` -------------------------------- ### Build Project Source: https://github.com/tanstack/pacer/blob/main/examples/angular/asyncDebounce/README.md Execute this command to compile the project. Build artifacts are stored in the 'dist/' directory. This command optimizes the application for performance by default. ```bash ng build ``` -------------------------------- ### Install TanStack Pacer Angular Adapter Source: https://github.com/tanstack/pacer/blob/main/docs/framework/angular/adapter.md Install the Angular Adapter for TanStack Pacer using npm. ```sh npm install @tanstack/angular-pacer ``` -------------------------------- ### throttle() - Usage Example Source: https://github.com/tanstack/pacer/blob/main/docs/reference/functions/throttle.md Demonstrates how to use the throttle function with different configurations for leading and trailing edge execution. ```APIDOC ## Example ### Basic throttling - max once per second ```ts import { throttle } from '@tanstack/pacer'; const updateUI = (data) => { console.log('UI updated with:', data); }; const throttledUpdateUI = throttle(updateUI, { wait: 1000 }); // Call the throttled function multiple times trottledUpdateUI('data1'); // Executes immediately trottledUpdateUI('data2'); // Will be ignored until 1 second passes setTimeout(() => throttledUpdateUI('data3'), 500); setTimeout(() => throttledUpdateUI('data4'), 1200); setTimeout(() => throttledUpdateUI('data5'), 1500); // Expected output: // UI updated with: data1 // UI updated with: data4 (or data5, depending on exact timing and trailing execution) ``` ### Configure leading/trailing execution ```ts import { throttle } from '@tanstack/pacer'; const saveData = (data) => { console.log('Saving data:', data); }; // Execute immediately on first call and again after delay if called during wait const throttledSaveData = throttle(saveData, { wait: 2000, leading: true, trailing: true }); throttledSaveData('initial data'); // Executes immediately setTimeout(() => throttledSaveData('intermediate data 1'), 500); setTimeout(() => throttledSaveData('intermediate data 2'), 1000); setTimeout(() => throttledSaveData('final data'), 2500); // Executes after the wait period // Expected output: // Saving data: initial data // Saving data: final data ``` ### Throttling without leading execution ```ts import { throttle } from '@tanstack/pacer'; const logMessage = (message) => { console.log(message); }; // Execute only after the wait period has passed since the last call const throttledLog = throttle(logMessage, { wait: 1500, leading: false, trailing: true }); throttledLog('First call'); // Ignored throttledLog('Second call'); // Ignored setTimeout(() => throttledLog('Third call'), 2000); // Executes after 1.5 seconds from the last call (which was 'Second call') // Expected output: // Third call ``` ``` -------------------------------- ### asyncQueue() - Configuration Options and Error Handling Source: https://github.com/tanstack/pacer/blob/main/docs/reference/functions/asyncQueue.md Explains the various configuration options available when creating an async queue and how errors are handled. ```APIDOC ### Configuration Options: - `concurrency`: Maximum number of concurrent tasks (default: 1) - `wait`: Time to wait between processing items (default: 0) - `maxSize`: Maximum number of items allowed in the queue (default: Infinity) - `getPriority`: Function to determine item priority - `addItemsTo`: Default position to add items ('back' or 'front', default: 'back') - `getItemsFrom`: Default position to get items ('front' or 'back', default: 'front') - `expirationDuration`: Maximum time items can stay in queue - `started`: Whether to start processing immediately (default: true) - `asyncRetryerOptions`: Configure retry behavior for task executions ### Error Handling: - If an `onError` handler is provided, it will be called with the error and queuer instance - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed - Both onError and throwOnError can be used together; the handler will be called before any error is thrown - The error state can be checked using the underlying AsyncQueuer instance ``` -------------------------------- ### useBatchedCallback Example Usage Source: https://github.com/tanstack/pacer/blob/main/docs/framework/preact/reference/functions/useBatchedCallback.md An example demonstrating how to use the useBatchedCallback hook to batch analytics events in a Preact application. ```APIDOC ## Example ```tsx // Batch analytics events const trackEvents = useBatchedCallback((events: AnalyticsEvent[]) => { sendAnalytics(events); }, { maxSize: 5, // Process when 5 events collected wait: 2000 // Or after 2 seconds }); // Use in event handlers ``` ``` -------------------------------- ### createQueuer Usage Examples Source: https://github.com/tanstack/pacer/blob/main/docs/framework/solid/reference/functions/createQueuer.md Illustrates different ways to use the createQueuer function, including default behavior, optimized state selection, and metric tracking. ```APIDOC ## Example Usage ### Default Behavior (No Reactive State Subscriptions) ```tsx const queue = createQueuer( (item) => { // process item synchronously console.log('Processing', item); }, { started: true, // Start processing immediately wait: 1000, // Process one item every second getPriority: (item) => item.priority // Process higher priority items first } ); // Add items to process queue.addItem('task1'); queue.addItem('task2'); ``` ### Opt-in to Track Specific State Changes (Optimized for UI Updates) ```tsx const queue = createQueuer( (item) => console.log('Processing', item), { started: true, wait: 1000 }, (state) => ({ items: state.items, isRunning: state.isRunning }) ); // Access selected state const { items, isRunning } = queue.state(); ``` ### Opt-in to Track Execution Metrics (Optimized for Progress Tracking) ```tsx const queue = createQueuer( (item) => console.log('Processing', item), { started: true, wait: 1000 }, (state) => ({ executionCount: state.executionCount, rejectionCount: state.rejectionCount }) ); // Access selected state const { executionCount, rejectionCount } = queue.state(); ``` ### Controlling the Scheduler ```tsx // Pause processing queue.stop(); // Resume processing queue.start(); ``` ### Unmount Behavior Customization ```tsx const queue = createQueuer(fn, { started: true, wait: 1000, onUnmount: (q) => q.flush() // Example: flush pending items on unmount }); ``` ``` -------------------------------- ### Initialize and Use AsyncBatcher Source: https://github.com/tanstack/pacer/blob/main/docs/reference/classes/AsyncBatcher.md Demonstrates how to create an AsyncBatcher instance with custom processing logic, batch size, wait time, and success/error callbacks. Items are added and processed automatically based on the configuration. ```typescript const batcher = new AsyncBatcher( async (items) => { const result = await processItems(items); console.log('Processing batch:', items); return result; }, { maxSize: 5, wait: 2000, onSuccess: (result) => console.log('Batch succeeded:', result), onError: (error) => console.error('Batch failed:', error) } ); batcher.addItem(1); batcher.addItem(2); // After 2 seconds or when 5 items are added, whichever comes first, // the batch will be processed and the result will be available // batcher.execute() // manually trigger a batch ``` -------------------------------- ### AsyncRateLimiter Example Usage Source: https://github.com/tanstack/pacer/blob/main/docs/reference/classes/AsyncRateLimiter.md Demonstrates how to create and use an AsyncRateLimiter instance to rate-limit an asynchronous function. ```APIDOC ## Example ```ts const rateLimiter = new AsyncRateLimiter( async (id: string) => await api.getData(id), { limit: 5, window: 1000, windowType: 'sliding', onError: (error) => { console.error('API call failed:', error); }, onReject: (limiter) => { console.log(`Rate limit exceeded. Try again in ${limiter.getMsUntilNextWindow()}ms`); } } ); // Will execute immediately until limit reached, then block // Returns the API response directly const data = await rateLimiter.maybeExecute('123'); ``` ``` -------------------------------- ### Example: Rate Limit API Calls with useAsyncRateLimitedCallback Source: https://github.com/tanstack/pacer/blob/main/docs/framework/preact/reference/functions/useAsyncRateLimitedCallback.md Demonstrates how to use the useAsyncRateLimitedCallback hook to limit asynchronous API calls to a maximum of 5 per minute using a sliding window. Includes an onReject handler for when the rate limit is reached. ```tsx // Rate limit async API calls to maximum 5 calls per minute with a sliding window const makeApiCall = useAsyncRateLimitedCallback( async (data: ApiData) => { return fetch('/api/endpoint', { method: 'POST', body: JSON.stringify(data) }); }, { limit: 5, window: 60000, // 1 minute windowType: 'sliding', onReject: () => { console.warn('API rate limit reached. Please wait before trying again.'); } } ); ``` -------------------------------- ### Install React Pacer Devtools Source: https://github.com/tanstack/pacer/blob/main/docs/devtools.md Install the necessary packages for React Pacer devtools. These are separate from the core React devtools. ```sh npm install @tanstack/react-devtools @tanstack/react-pacer-devtools ``` -------------------------------- ### Build and Watch for Changes Source: https://github.com/tanstack/pacer/blob/main/CONTRIBUTING.md To test your changes in your own projects, build and watch for changes using these commands. ```bash pnpm build ``` ```bash pnpm dev ``` -------------------------------- ### Create a Changeset Source: https://github.com/tanstack/pacer/blob/main/CONTRIBUTING.md Create a changeset (changelog entry) for your changes by running this command. ```bash pnpm changeset ``` -------------------------------- ### Basic Debouncer Example Source: https://github.com/tanstack/pacer/blob/main/docs/framework/solid/adapter.md A simple example of creating a debouncer to delay the execution of a function, useful for input event handling to avoid excessive calls. ```tsx import { createDebouncer } from '@tanstack/solid-pacer' function SearchComponent() { const debouncer = createDebouncer( (query: string) => { console.log('Searching for:', query) // Perform search }, { wait: 500 } ) return ( debouncer.maybeExecute(e.currentTarget.value)} placeholder="Search..." /> ) } ``` -------------------------------- ### Default Unmount Behavior Example Source: https://github.com/tanstack/pacer/blob/main/docs/framework/solid/reference/functions/createAsyncQueuer.md This example demonstrates the default unmount behavior where in-flight tasks are aborted. It's suitable when no reactive state subscriptions are needed. ```tsx // Default behavior - no reactive state subscriptions const asyncQueuer = createAsyncQueuer(async (item) => { // process item return await fetchData(item); }, { initialItems: [], concurrency: 2, maxSize: 100, started: false, onSuccess: (result) => { console.log('Item processed:', result); }, onError: (error) => { console.error('Processing failed:', error); } }); ``` -------------------------------- ### Debounced Value Example Source: https://github.com/tanstack/pacer/blob/main/docs/framework/solid/reference/functions/createDebouncedValue.md Demonstrates creating a debounced search query and using it to fetch results. Includes an example of opting into reactive updates for pending state. ```tsx // Default behavior - no reactive state subscriptions const [searchQuery, setSearchQuery] = createSignal(''); const [debouncedQuery, debouncer] = createDebouncedValue(searchQuery, { wait: 500 // Wait 500ms after last change }); // Opt-in to reactive updates when pending state changes (optimized for loading indicators) const [debouncedQuery, debouncer] = createDebouncedValue( searchQuery, { wait: 500 }, (state) => ({ isPending: state.isPending }) ); // debouncedQuery will update 500ms after searchQuery stops changing createEffect(() => { fetchSearchResults(debouncedQuery()); }); // Access debouncer state via signals console.log('Is pending:', debouncer.state().isPending); // Control the debouncer debouncer.cancel(); // Cancel any pending updates ``` -------------------------------- ### Create and Use Async Batcher Source: https://github.com/tanstack/pacer/blob/main/docs/reference/functions/asyncBatch.md Example of creating an async batcher with specified batch size, wait time, and success/error handlers. Items are added to the batcher, and processing is triggered when the batch is full. ```typescript const batchItems = asyncBatch( async (items) => { const result = await processApiCall(items); console.log('Processing:', items); return result; }, { maxSize: 3, wait: 1000, onSuccess: (result) => console.log('Batch succeeded:', result), onError: (error) => console.error('Batch failed:', error) } ); batchItems(1); batchItems(2); batchItems(3); // Triggers batch processing ``` -------------------------------- ### Install React Devtools Adapter and Plugin Source: https://github.com/tanstack/pacer/blob/main/docs/installation.md Install the React devtools adapter and Pacer devtools plugin as dev dependencies to inspect and monitor your pacers in React applications. ```bash npm install --save-dev @tanstack/react-devtools @tanstack/react-pacer-devtools ```