JavaScript Learning Notes Collation _settimeout Application _ Basics

Source: Internet
Author: User
Tags eval setinterval

T application of Settimeou

var ids = [];
function Foo1 (i) {
  this.i = i;
  Console.log (' i = ' +i ');
  Ids[0] = settimeout ((function () {
    foo1 (i);
  }), 1000);
function Foo2 (j) {
  this.j = j;
  Console.log (' j = ' +j ');
  IDS[1] = settimeout ((function () {
    foo2 (j);
  }), 1000);
Foo1 (2);
Foo2 (3);
Cleartimeout (Ids[0]);
Cleartimeout (Ids[1]);

When settimeout (F,n) is invoked, it returns an ID identifier and plans to call the F function after approximately n milliseconds in the future. The F function is executed only once (recursive execution can execute every n milliseconds), based on the JavaScript engine's timing strategy, and the essentially single-threaded operation, so other code runs may block the thread. Therefore, there is no guarantee that the function will be invoked at the time specified by settimeout. Prevent blocking by using the SetTimeout function inside the callback function!

JavaScript is asynchronous, settimeout only executes the callback function once, but setinterval executes the function once every X millisecond. But the use of this function is discouraged. When execution of the callback function is blocked, SetInterval still publishes more callback instructions. At very small intervals, this causes the callback function to accumulate.

SetTimeout and SetInterval also accept the case where the first argument is a string. This feature should never be used because it uses a hidden eval internally, because Eval is not called directly in this case, so the string passed to SetTimeout is executed from the global scope and is not recommended when the timer function is invoked In order to pass arguments to the callback function using the form of a string; When you need to pass parameters to the callback function, you can create an anonymous function that executes the true callback function within the function;

Onscolll,onresize, etc. is very performance, if we change to Ajax request, then zoom in a window will repeatedly trigger a number of AJAX requests, the following we try to use the function throttle operation to try it, of course, add a settimeout () the timer is good,

The first method of encapsulation

var count = 0;
function Ocount () {
  count++;
  Console.log (count);
}
Window.onresize = function () {
  delayfun (ocount)
};

function Delayfun (method, Thisarg) {
  cleartimeout (method.props);
  Method.props = settimeout (function () {
    method.call (thisarg)
  },)
}

The second method of encapsulation

Construct a closure that uses closures to form a private scope for storing timer timers, which are introduced in the form of parameters.

var count = 0;
function Ocount () {
  count++;
  Console.log (count);
}
var funs= delayfun (ocount,100);
Window.onresize = function () {
  funs ()
};

function Delayfun (func, wait) {
  var timer = null;
  return function () {
    var context = This,
      args = arguments;
    Cleartimeout (timer);
    Timer = settimeout (function () {
      func.apply (context, args);
    }, wait)
  };
}

Optimized for the second method, performance would be better

This returns a function, which will not be executed if it is invoked without interruption. The function calls it again after it stops calling N milliseconds before it is executed. If there is a pass ' immediate ' parameter, the function is immediately scheduled into the execution queue without delay.

function Delayfun (func, wait, immediate) {
  var timeout;
  return function () {
    var context = this, args = arguments;
    var later = function () {
      timeout = null;
      if (!immediate) func.apply (context, args);
    var callnow = immediate &&!timeout;
    Cleartimeout (timeout);
    Timeout = settimeout (later, wait);
    if (Callnow) func.apply (context, args);
  }

;}; Usage
var myefficientfn = Delayfun (function () {
  //All heavy operations
};
Window.addeventlistener (' resize ', MYEFFICIENTFN);

function does not allow callback functions to execute more than once in a specified time. This function is particularly important when assigning a callback function for an event that is frequently triggered.

SetTimeout is so powerful, can we use it extensively in the project?

Personally, I do not recommend, in our business, basically prohibit the use of settimeout in the business logic, because I see a lot of ways to use the problem is difficult to solve, settimeout as a hack way.

For example, we use this instance before an instance is initialized, and the wrong solution is to use an instance with a settimeout to ensure that the instance is initialized first.

Why the mistake? This is actually the way to use hack.

The first is to bury the pit, disrupting the life cycle of the module

Second, when problems arise, settimeout is actually difficult to debug.

I think the right way to use it is to look at the lifecycle (refer to the lifecycle of the software) and take the instantiation to the pre-use execution

The above is a small series for everyone to bring the JavaScript learning notes to organize the application of all the content of _settimeout, hope to help you, a lot of support cloud Habitat Community ~

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.