JavaScript scheduling task background running method _javascript Tips

Source: Internet
Author: User

Even if you forget all the knowledge of JavaScript, you will not forget: it is blocked.

Imagine a magical elf living in your browser that is responsible for the normal operation of the browser. Whether rendering HTML, responding to menu commands, screen rendering, handling mouse clicks, or executing JavaScript functions, everything is handled by a small elf. It's too busy to handle one thing at a time. If you throw it a bunch of tasks at the same time, it lists a long to-do list and completes them sequentially.

It is often hoped that JavaScript that initializes components and event handling can be executed as soon as possible. However, some of the less important background tasks do not directly affect the user experience, such as:

Record statistics

Send data to a social network (or add a ' share ' button)

Pre-loading content

Preprocessing or pre-render HTML

They are not strict with timing requirements, but are executed in order for the page to remain responsive until the user scrolls the page or interacts with the content.

One of the choices is the WEB workers, which can execute code at the same time as a separate thread. For preload and preprocessing it's good, but you don't have permission to access or update the DOM directly. You can avoid this in your own code, but there's no guarantee that Third-party scripts like Google Analytics never need this.

Another option is settimeout, such as settimeout (dosomething, 1); Once the other immediate execution completes, the browser executes the dosomething () function. In fact, it was placed at the bottom of the to-do list. Unfortunately, the function will be invoked without regard to the processing requirements.

#requestIdleCallback

Requestidlecallback is a new API that is used to perform less important background planning tasks when the browser is breathing a bit. Inevitably reminiscent of requestanimationframe, perform a function update animation before the next redraw. Want to learn more about poking here: use Requestanimationframe to do simple animations.

Requestidlecallback Characteristics Monitoring:

if (' Requestidlecallback ' in window) {
 //Requestidlecallback supported
 requestidlecallback (backgroundtask);
else {
 //no support-do something else
 settimeout (backgroundTask1, 1);
 SetTimeout (BackgroundTask2, 1);
 SetTimeout (BACKGROUNDTASK3, 1);
}

You can also specify configuration parameter objects, such as timeout,

 
  

Make sure that the function is invoked within 3 seconds, regardless of whether the browser is idle.

When the deadline object passes in the following parameters, Requestidlecallback performs only one callback:

didtimeout--set to True if optional timeout trigger
Timeremaining ()--function returns the number of milliseconds left to perform a task
Timeremaining () allocates up to 50ms for task execution, exceeding this limit, and does not stop the task, but it is best to recall requestidlecallback to arrange further processing.

Let's create a simple example that allows several tasks to be executed in sequence. A function reference for a task is stored in an array:

Array of functions to be executed
var task = [
  background1,
  background2,
  background3
];
if (' Requestidlecallback ' in window) {
 //support Requestidlecallback
 requestidlecallback (backgroundtask);
}
else {
 //unsupported-immediately execute All Tasks
 while (task.length) {
  settimeout (Task.shift (), 1);
 }
}
Requestidlecallback callback function function
Backgroundtask (deadline) {
 //if present, perform the next task while
 ( Deadline.timeremaining () > 0 && task.length > 0) {
  task.shift () ();
 }
 If necessary, arrange further tasks
 if (Task.length > 0) {
  requestidlecallback (backgroundtask);
 }
}

What should not be done between the #一次 Requestidlecallback?

Paul Lewis mentions in his article that a requestidlecallback task should be cut into small pieces. It does not apply to unpredictable time situations (such as manipulating the DOM, using Requestanimationframe callbacks better). Resolving (or rejecting) promises should also be cautious, even if there is no more time remaining, and the callback function is executed immediately after the idle callback completes.

#requestIdleCallback Browser Support

Requestidlecallback is an experimental feature, the specification is still unstable and it is not uncommon to encounter API changes. Chrome 47 has supported ... Should be available before the end of 2015. Opera should be followed. Both Microsoft and Mozilla are considering whether the API should support promises. Apple does not bird as usual.

Paul Lewis (mentioned above) wrote a simple requestidlecallback shim that simulates the idle monitoring behavior of browsers, but not a polyfill (shim and Polyfill differences).

Requestidlecallback shim code is as follows:

/*! * Copyright Google Inc.
 All rights reserved. * * Licensed under the Apache License, Version.
 (the "License");
 * You could not use this file, except in compliance with the License.
 * Obtain a copy of the License at * * http://www.apache.org/licenses/license-. * Unless required by applicable or agreed to in writing, software * Distributed under the License is distributed O n an ' as is ' basis, * without warranties or CONDITIONS to any KIND, either express * or implied.
 The License for the specific language governing * permissions and limitations the under. * * * * @see https://developers.google.com/web/updates///using-requestidlecallback * * * Window.requestidlecallback =
 Window.requestidlecallback | |
  Function (CB) {var start = Date.now (); Return settimeout (function () {CB ({didtimeout:false, timeremaining:function () {return Math.max ()-(
    Date.now ()-start);
  }
   });
 }, ); } Window.cancelidlecallback = Window.canCelidlecallback | |
 function (ID) {cleartimeout (ID); }

PS: How to run a scheduled task

1, run GPEDIT. MSC

2, select the Computer Configuration

---Windows settings
---security settings
---local policy
---user Rights Assignment
Double-click the right to access this computer from the network
Add the user name you want to the list.

3,---security settings

---security options
Turn on allow server Operators to schedule tasks

4 、-----Local Policy

---Log on as a batch job
Add the user name you want to the list.

5 、-----Local Policy

---Allow computers and users to be trusted for delegation
Add the user name you want to the list.
It is best to be an administrator user.

Prompt code if task schedule fails to start: 0x80041315

WORKAROUND: There are two possibilities, one is that the "task Scheduler" service in the system does not start, you can type "Services.msc" in the run to see if the Task Scheduler service is set to disabled, if so, just double-click it to change the startup type to Auto, reset a scheduled task to execute.

If your current account is set up for automatic login, and its login password is empty, it may also cause the task schedule to not be executed on time, in XP Professional Edition, you need to run "gpedit.msc" to edit Group Policy: Expand Computer Configuration →windows settings → security settings → local Computer policy → security options Double-click the "account: local account with blank password allows console logon only" item on the right, select Disabled in the pop-up dialog box.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.