Home > Web Front-end > JS Tutorial > How to Schedule Background Tasks in JavaScript

How to Schedule Background Tasks in JavaScript

William Shakespeare
Release: 2025-02-18 09:04:11
Original
263 people have browsed it

How to Schedule Background Tasks in JavaScript

Core points

  • JavaScript is a blocking language that can only perform one task at a time, which can cause long-running scripts to make the browser unresponsive. However, less important background tasks can be scheduled to run without directly affecting the user experience.
  • requestIdleCallback is an API that allows scheduling unnecessary tasks when the browser is idle, similar to the functionality of requestAnimationFrame. It can be used with the timeout option to ensure that tasks run within a set time range, even if the browser is not idle.
  • requestIdleCallback is an experimental feature with limited browser support and is not suitable for tasks that perform unpredictable time or to resolve Promise tasks. For unsupported browsers or tasks that require direct access to the DOM, alternatives such as Web Workers or setTimeout can be used.

If you forget everything else in JavaScript, always remember this: It blocks. Imagine a magical processing wizard making your browser work. Whether it's rendering HTML, responding to menu commands, drawing on the screen, handling mouse clicks, or running JavaScript functions, all of this is handled by a single sprite. Like most of us, elves can only do one thing at a time. If we throw a lot of tasks at the elves, they are added to a large to-do list and processed in order. Everything else stops when the sprite encounters a script tag or must run a JavaScript function. The code (if needed) will be downloaded and run immediately before further events or rendering is processed. This is necessary because your script can do anything: load more code, delete each DOM element, redirect to another URL, etc. Even with two or more sprites, other sprites need to stop working when the first sprite processes your code. This is blocking. This is why long-running scripts cause the browser to be unresponsive. You usually want JavaScript to run as soon as possible, because the code initializes widgets and event handlers. However, there are some less important backend tasks that will not directly affect the user experience, such as:

  • Record analysis data
  • Send data to social networks (or add 57 "Share" buttons)
  • Prefetch content
  • Preprocessing or pre-rendering HTML

These are not time-critical tasks, but to keep the page responsive, they should not run when the user scrolls or interacts with the content. One option is to use Web Workers, which can run code concurrently in a separate thread. This is a great choice for prefetching and processing, but you do not allow direct access or update of the DOM. You can avoid this in your own scripts, but you can't guarantee that third-party scripts such as Google Analytics will never need it. Another possibility is setTimeout, for example setTimeout(doSomething, 1);. The browser will execute the doSomething() function after other immediately executed tasks are completed. In fact, it is placed at the bottom of the to-do list. Unfortunately, the function is called regardless of the processing requirements.

requestIdleCallback

requestIdleCallback is a new API designed to schedule non-essential backend tasks during those moments of the browser's breathing. It reminds you of requestAnimationFrame, which calls a function to update the animation before the next repaint. You can read more about requestAnimationFrame here: Simple animation using requestAnimationFrame

We can check whether it supports it like this requestIdleCallback:

if ('requestIdleCallback' in window) {
  // requestIdleCallback 受支持
  requestIdleCallback(backgroundTask);
} else {
  // 不支持 - 执行其他操作
  setTimeout(backgroundTask1, 1);
  setTimeout(backgroundTask2, 1);
  setTimeout(backgroundTask3, 1);
}
Copy after login
Copy after login

You can also specify option object parameters using timeout (in milliseconds), for example:

requestIdleCallback(backgroundTask, { timeout: 3000 });
Copy after login
Copy after login

This ensures that your function is called within the first three seconds, regardless of whether the browser is idle or not. requestIdleCallback Call your function only once and pass a deadline object with the following properties:

  • didTimeout — Set to true
  • if the optional timeout trigger is set to true
  • timeRemaining()
  • — Function that returns the remaining milliseconds of the executable task

timeRemaining()requestIdleCallback Your task will be assigned no more than 50 milliseconds of run time. It does not stop tasks that exceed this limit, but it is better to call

again to schedule further processing. Let's create a simple example that performs multiple tasks in order. Tasks are stored in an array as function references:
// 要运行的函数数组
var task = [
  background1,
  background2,
  background3
];

if ('requestIdleCallback' in window) {
  // requestIdleCallback 受支持
  requestIdleCallback(backgroundTask);
} else {
  // 不支持 - 尽快运行所有任务
  while (task.length) {
    setTimeout(task.shift(), 1);
  }
}

// requestIdleCallback 回调函数
function backgroundTask(deadline) {
  // 如果可能,运行下一个任务
  while (deadline.timeRemaining() > 0 && task.length > 0) {
    task.shift()();
  }

  // 如果需要,安排进一步的任务
  if (task.length > 0) {
    requestIdleCallback(backgroundTask);
  }
}
Copy after login
Copy after login

requestIdleCallbackActions that should not be performed in

?

requestIdleCallback As Paul Lewis points out in his blog post on this topic, the work you perform in requestAnimationFrame should be divided into small pieces. It does not work for anything with unpredictable execution time (such as operating the DOM, which is best done using the

callback). You should also be careful to resolve (or reject) the Promise, as the callback will be executed immediately after the idle callback is completed, even if there is no more time left. <🎜>

requestIdleCallback Browser support

requestIdleCallback is an experimental feature, and the specifications are still changing, so don't be surprised when you encounter API changes. It is supported in Chrome 47…this should be available by the end of 2015. Opera should also get this feature soon. Both Microsoft and Mozilla are considering using the API, and it sounds promising. Apple has no news as usual. If you want to try it out today, the best way is to use Chrome Canary (an updated version of Chrome that is not as good as the former, but has the latest cool features). Paul Lewis (mentioned above) creates a simple requestIdleCallback shim. This implements the description of the API, but it is not a polyfill that can simulate browser idle detection behavior. It uses the method of using setTimeout like the example above, but it's a good option if you want to use the API without object detection and code forking. While there is limited support today, requestIdleCallback may be an interesting tool to help you maximize your web performance. But what do you think? I'd love to hear your thoughts in the comments section below.

FAQ on Scheduling Backend Tasks in JavaScript (FAQ)

What is the background task API in JavaScript?

Background Tasks in JavaScript The API is a powerful tool that allows developers to schedule tasks running in the background, even if the main thread is idle. This API is especially suitable for tasks that require a lot of compute or network requests, as it allows these tasks to be performed without blocking the main thread and potentially leading to a bad user experience. The backend task API is part of the larger Web API provided by modern browsers, providing a more efficient and performance-oriented way to handle backend tasks than the traditional setTimeout or setInterval methods.

How is the

Background Task API different from setTimeout and setInterval?

The

setTimeout and setInterval functions are traditional methods in JavaScript that are used to schedule tasks to run after a specific delay or at regular intervals. However, these approaches have some limitations, especially in terms of performance. They run on the main thread, which means that if they take too long to complete, they can block other tasks and can lead to a bad user experience. On the other hand, the background task API runs tasks in the background, separate from the main thread. This means it can handle more intensive tasks without affecting the performance of the main thread.

Can I use the background task API in all browsers?

The backend task API is a relatively new addition to the Web API provided by modern browsers, so it may not be supported in all browsers. When planning to use any API in your project, it is always best to check the current support level of the API you plan to use. Websites like Can I Use provide the latest information on the support levels of various APIs in different browsers.

How to use the background task API to schedule tasks running in the background?

To use the background task API to schedule tasks, you can use the requestIdleCallback method. This method takes the callback function as its first parameter, which will be executed when the browser is idle. Here is a basic example:

if ('requestIdleCallback' in window) {
  // requestIdleCallback 受支持
  requestIdleCallback(backgroundTask);
} else {
  // 不支持 - 执行其他操作
  setTimeout(backgroundTask1, 1);
  setTimeout(backgroundTask2, 1);
  setTimeout(backgroundTask3, 1);
}
Copy after login
Copy after login

How to cancel scheduled background tasks?

If you need to cancel background tasks scheduled using the requestIdleCallback method, you can use the cancelIdleCallback method. This method takes the ID returned by requestIdleCallback as its parameter. Here is an example:

requestIdleCallback(backgroundTask, { timeout: 3000 });
Copy after login
Copy after login
What is the use of the timeout option in

requestIdleCallback?

The timeout option in

requestIdleCallback specifies the maximum time (in milliseconds) the browser should wait before running the callback, even if it is not idle. This is useful if your background tasks need to run within a specific time frame.

How to deal with errors in background tasks?

Handling errors in background tasks scheduled using the background task API are similar to handling errors in any other JavaScript code. You can use the try/catch block to catch any errors that occur during task execution. Here is an example:

// 要运行的函数数组
var task = [
  background1,
  background2,
  background3
];

if ('requestIdleCallback' in window) {
  // requestIdleCallback 受支持
  requestIdleCallback(backgroundTask);
} else {
  // 不支持 - 尽快运行所有任务
  while (task.length) {
    setTimeout(task.shift(), 1);
  }
}

// requestIdleCallback 回调函数
function backgroundTask(deadline) {
  // 如果可能,运行下一个任务
  while (deadline.timeRemaining() > 0 && task.length > 0) {
    task.shift()();
  }

  // 如果需要,安排进一步的任务
  if (task.length > 0) {
    requestIdleCallback(backgroundTask);
  }
}
Copy after login
Copy after login

Can I use the background task API in Node.js?

The backend task API is part of the Web API provided by modern browsers, so it is not available in Node.js by default. However, there are other ways to run background tasks in Node.js, such as using worker threads or child processes.

Can I use the background task API with Promise or async/await?

The background task API does not return a Promise, so it cannot be used directly with async/await. However, if you need to use it in an asynchronous context, you can wrap the requestIdleCallback method in a Promise. Here is an example:

window.requestIdleCallback(() => {
  // 您的后台任务在此处
});
Copy after login

What are some use cases of the backend task API?

Background Tasks API is useful for any task that requires a lot of computation or network requests, as it allows these tasks to be executed without blocking the main thread. Some examples of use cases may include fetching and processing data from the API, performing complex calculations, or updating the UI based on user interactions.

The above is the detailed content of How to Schedule Background Tasks in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template