A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://developer.mozilla.org/en-US/docs/Web/API/TaskController below:

TaskController - Web APIs | MDN

Note: Additional "live" examples can be found in: Prioritized Task Scheduling API Examples.

First we create a task controller, setting the priority of its associated signal to user-blocking.

// Create a TaskController, setting its signal priority to 'user-blocking'
const controller = new TaskController({ priority: "user-blocking" });

We then add an event listener for prioritychange events (here addEventListener() is called, but we could instead assign a handler to TaskSignal.onprioritychange). The handler uses previousPolicy on the event to get the original priority and TaskSignal.priority on the event target to get the new priority.

// 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}.`);
});

We can also listen for abort events as shown below. This same approach would be used if the controller was an AbortController.

controller.signal.addEventListener("abort", (event) => {
  console.log("Task aborted");
});

Next we post the task, passing the controller signal in the optional argument. In this case the task is just an arrow function that resolves the promise by returning some text. We use then and catch to handle when the task resolves or is rejected, logging the return text or the error in each case. Note that in a later code block we abort the task, so only the catch() block will actually be run!

// Post task using the controller's signal.
// The signal priority sets the initial priority of the task
scheduler
  .postTask(() => "Task execute", { signal: controller.signal })
  .then((taskResult) => {
    console.log(`${taskResult}`);
  }) // Aborted (won't run)
  .catch((error) => {
    console.log(`Catch error: ${error}`);
  }); // Log error

We can use the controller to manage the task. Here we can change the priority using TaskController.setPriority(). This will trigger the associated prioritychange event.

// Change the priority to 'background' using the controller
controller.setPriority("background");

Finally, the task can be aborted by calling abort() on the controller.

// Abort the task
controller.abort();

The console output of this example would be:

The priority changed from user-blocking to background.
Task aborted
Catch error: AbortError

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4