Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Scheduler: postTask() method

Limited availability

Note: This feature is available inWeb Workers.

ThepostTask() method of theScheduler interface is used for adding tasks to bescheduled according to theirpriority.

The method allows users to optionally specify a minimum delay before the task will run, a priority for the task, and a signal that can be used to modify the task priority and/or abort the task.It returns a promise that is resolved with the result of the task callback function, or rejected with the abort reason or an error thrown in the task.

Task priority can bemutable or immutable.If the task priority will never need to change then it should be set using theoptions.priority parameter (any priority set through a signal will then be ignored).You can still pass anAbortSignal (which has no priority) orTaskSignal to theoptions.signal parameter for aborting the task.

If the task priority might need to be changed theoptions.priority parameter must not be set.Instead aTaskController should be created and itsTaskSignal should be passed tooptions.signal.The task priority will be initialized from the signal priority, and can later be modified using the signal's associatedTaskController.

If no priority is set then the task priority defaults to"user-visible".

If a delay is specified and greater than 0, then the execution of the task will be delayed for at least that many milliseconds.Otherwise the task is immediately scheduled for prioritization.

Syntax

js
postTask(callback)postTask(callback, options)

Parameters

callback

An callback function that implements the task.The return value of the callback is used to resolve the promise returned by this function.

optionsOptional

Task options, including:

priorityOptional

The immutablepriority of the task.One of:"user-blocking","user-visible","background".If set, this priority is used for the lifetime of the task and priority set on thesignal is ignored.

signalOptional

ATaskSignal orAbortSignal that can be used to abort the task (from its associated controller).

If theoptions.priority parameter is set then the task priority cannot be changed, and any priority on the signal is ignored.Otherwise, if the signal is aTaskSignal its priority is used to set the initial task priority, and the signal's controller may later use it to change the task priority.

delayOptional

The minimum amount of time after which the task will be added to the scheduler queue, in whole milliseconds.The actual delay may be higher than specified, but will not be less.The default delay is 0.

Return value

Returns aPromise that is resolved with the return value of thecallback function, or which may be rejected with thesignal's abort reason (AbortSignal.reason).The promise may also be rejected with an error thrown by the callback during execution.

Examples

The following examples are slightly simplified versions of the live examples provided inPrioritized Task Scheduling API > Examples.

Feature checking

Check whether prioritized task scheduling is supported by testing for thescheduler property in the global scope (such asWindow.scheduler in window's scope orWorkerGlobalScope.scheduler in worker's scope).

For example, the code below logs "Feature: Supported" if the API is supported on this browser.

js
// Check that feature is supportedif ("scheduler" in globalThis) {  console.log("Feature: Supported");} else {  console.error("Feature: NOT Supported");}

Basic usage

Tasks are posted specifying a callback function (task) in the first argument, and an optional second argument that can be used to specify a task priority, signal, and/or delay.The method returns aPromise that resolves with the return value of the callback function, or rejects with either an abort error or an error thrown in the function.

Because it returns a promise,postTask() can bechained with other promises.Below we show how to wait on the promise to resolve usingthen or reject usingcatch.The priority is not specified, so the default priority ofuser-visible will be used.

js
// A function that defines a taskfunction myTask() {  return "Task 1: user-visible";}// Post task with default priority: 'user-visible' (no other options)// When the task resolves, Promise.then() logs the result.scheduler  .postTask(myTask, { signal: abortTaskController.signal })  .then((taskResult) => console.log(`${taskResult}`)) // Log resolved value  .catch((error) => console.error("Error:", error)); // Log error or abort

The method can also be used withawait inside anasync function.The code below shows how you might use this approach to wait on auser-blocking task.

js
function myTask2() {  return "Task 2: user-blocking";}async function runTask2() {  const result = await scheduler.postTask(myTask2, {    priority: "user-blocking",  });  console.log(result); // 'Task 2: user-blocking'.}runTask2();

Permanent priorities

Task priorities may be set usingpriority parameter in the optional second argument.Priorities that are set in this way cannot be changed (areimmutable).

Below we post two groups of three tasks, each member in reverse order of priority.The final task has the default priority.When run, each task simply logs it's expected order (we're not waiting on the result because we don't need to in order to show execution order).

js
// three tasks, in reverse order of priorityscheduler.postTask(() => console.log("bkg 1"), { priority: "background" });scheduler.postTask(() => console.log("usr-vis 1"), {  priority: "user-visible",});scheduler.postTask(() => console.log("usr-blk 1"), {  priority: "user-blocking",});// three more tasks, in reverse order of priorityscheduler.postTask(() => console.log("bkg 2"), { priority: "background" });scheduler.postTask(() => console.log("usr-vis 2"), {  priority: "user-visible",});scheduler.postTask(() => console.log("usr-blk 2"), {  priority: "user-blocking",});// Task with default priority: user-visiblescheduler.postTask(() => {  console.log("usr-vis 3 (default)");});

The expected output is shown below: tasks are executed in priority order, and then declaration order.

usr-blk 1usr-blk 2usr-vis 1usr-vis 2usr-vis 3 (default)bkg 1bkg 2

Changing task priorities

Task priorities can also take their initial value from aTaskSignal passed topostTask() in the optional second argument.If set in this way, the priority of the taskcan then be changed using the controller associated with the signal.

Note:Setting and changing task priorities using a signal only works when theoptions.priority argument topostTask() is not set, and when theoptions.signal is aTaskSignal (and not anAbortSignal).

The code below first shows how to create aTaskController, setting the initial priority of its signal touser-blocking in theTaskController() constructor.

We then useaddEventListener() to add an event listener to the controller's signal (we could alternatively use theTaskSignal.onprioritychange property to add an event handler).The event handler usespreviousPriority on the event to get the original priority andTaskSignal.priority on the event target to get the new/current priority.

js
// Create a TaskController, setting its signal priority to 'user-blocking'const controller = new TaskController({ priority: "user-blocking" });// Listen for 'prioritychange' events on the controller's signal.controller.signal.addEventListener("prioritychange", (event) => {  const previousPriority = event.previousPriority;  const newPriority = event.target.priority;  console.log(`Priority changed from ${previousPriority} to ${newPriority}.`);});

Finally, the task is posted, passing in the signal, and then we immediately change the priority tobackground by callingTaskController.setPriority() on the controller.

js
// Post task using the controller's signal.// The signal priority sets the initial priority of the taskscheduler.postTask(() => console.log("Task 1"), { signal: controller.signal });// Change the priority to 'background' using the controllercontroller.setPriority("background");

The expected output is shown below.Note that in this case the priority is changed before the task is executed, but it could equally have been changed while the task was running.

js
// Expected output// Priority changed from user-blocking to background.// Task 1

Aborting tasks

Tasks can be aborted using eitherTaskController andAbortController, in exactly the same way.The only difference is that you must useTaskController if you also want to set the task priority.

The code below creates a controller and passes its signal to the task.The task is then immediately aborted.This causes the promise to be rejected with anAbortError, which is caught in thecatch block and logged.Note that we could also have listened for theabort event fired on theTaskSignal orAbortSignal and logged the abort there.

js
// Declare a TaskController with default priorityconst abortTaskController = new TaskController();// Post task passing the controller's signalscheduler  .postTask(() => console.log("Task executing"), {    signal: abortTaskController.signal,  })  .then((taskResult) => console.log(`${taskResult}`)) // This won't run!  .catch((error) => console.error("Error:", error)); // Log the error// Abort the taskabortTaskController.abort();

Delaying tasks

Tasks can be delayed by specifying an integer number of milliseconds in theoptions.delay parameter topostTask().This effectively adds the task to the prioritized queue on a timeout, as might be created usingsetTimeout().Thedelay is the minimum amount of time before the task is added to the scheduler; it may be longer.

The code below shows two tasks added (as arrow functions) with a delay.

js
// Post task as arrow function with delay of 2 secondsscheduler  .postTask(() => "Task delayed by 2000ms", { delay: 2000 })  .then((taskResult) => console.log(`${taskResult}`));scheduler  .postTask(() => "Next task should complete in about 2000ms", { delay: 1 })  .then((taskResult) => console.log(`${taskResult}`));

Specifications

Specification
Prioritized Task Scheduling
# dom-scheduler-posttask

Browser compatibility

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp