How to sort JavaScript learning notes _ setTimeout and javascript

Source: Internet
Author: User

How to sort JavaScript learning notes _ setTimeout and javascript

SetTimeou t Application

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 called, it returns an ID and plans to call the f function after about n milliseconds in the future. The f function is executed only once (recursive execution can be performed every n milliseconds), the timing policy based on the JavaScript engine, and the essentially single-thread running mode, therefore, the running of other code may block this thread. Therefore, the function cannot be called at the time specified by setTimeout. Use the setTimeout function inside the callback function to prevent blocking!

JavaScript is asynchronous. setTimeout only executes the callback function once, but setInterval executes the function once every X milliseconds. However, this function is not encouraged. When the execution of the callback function is blocked, setInterval will still issue more callback commands. At a very small interval, this will cause the callback function to accumulate.

SetTimeout and setInterval also accept the case where the first parameter is a string. This feature is never used because it uses hidden eval internally. Because eval is not directly called in this case, the string passed to setTimeout will be executed from the global scope, we recommend that you do not use a string to pass parameters to the callback function when calling the timer function. When you need to pass parameters to the callback function, you can create an anonymous function, execute real callback functions in the function;

Onscolll, onresize, and so on are very performance-consuming. If we replace them with ajax requests, the window will be scaled once, and multiple ajax requests will be triggered consecutively, next, let's try the function throttling operation. Of course, just add a settimeout () timer,

First Encapsulation Method

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)  }, 200)}

Second Encapsulation Method

Construct a closure and use the closure to form a private scope to store the timer. timer is introduced by passing 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)  };}

To optimize the second method, the performance will be better.

A function is returned here. If it is continuously called, it will not be executed. This function can be executed only after it is called again N milliseconds after it is stopped. If the 'immediate' parameter is passed, the function will be immediately arranged in 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}, 250); window. addEventListener ('resize', myEfficientFn );

The callback function cannot be executed more than once within the specified time. This function is especially important when a callback function is assigned for an event that is frequently triggered.

If setTimeout is so powerful, can we use it in a large amount in projects?

I personally do not recommend that you use setTimeout in your business logic, because many of the methods I see are difficult to solve, setTimeout is used as an hack.

For example, before an instance is initialized, we use this instance. The error solution is to add a setTimeout when using the instance to ensure that the instance is initialized first.

Why is the error? Here is the hack method.

The first is to bury the pitfalls and disrupt the life cycle of the module.

Second, it is difficult to debug setTimeout when a problem occurs.

I think the correct way to use it is to look at the life cycle (refer to the life cycle of the software) and refer to the example before use.

The above is all the content of the _ setTimeout app for the JavaScript study notes provided by xiaobian. I hope it will be helpful to you and provide more support to the customer's home ~

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.