Home > Web Front-end > JS Tutorial > body text

Detailed explanation of the usage of basic JavaScript functions debounce, poll and once instances

伊谢尔伦
Release: 2018-05-26 09:13:01
Original
5671 people have browsed it

debounce

For high energy consumption events, the debounce function is a good solution. If you don't use the debounce function for scroll, resize, and key* events, then you are almost making a mistake. The following debounce function can keep your code efficient:

// 返回一个函数,如果它被不间断地调用,它将不会得到执行。该函数在停止调用 N 毫秒后,再次调用它才会得到执行。如果有传递 ‘immediate' 参数,会马上将函数安排到执行队列中,而不会延迟。
function debounce(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);
  };
};
 
// 用法
var myEfficientFn = debounce(function() {
    
// 所有繁重的操作
}, 250);
window.addEventListener('resize', myEfficientFn);
Copy after login

The debounce function does not allow the callback function to be executed more than once within a specified time. This function is particularly important when assigning a callback function to an event that will be triggered frequently.

poll

Although the debounce function is mentioned above, you cannot insert an event to determine the required state if the event does not exist. Then you need to check whether the status meets your requirements every once in a while.

function poll(fn, callback, errback, timeout, interval) {
  var endTime = Number(new Date()) + (timeout || 2000);
  interval = interval || 100;
 
  (function p() {
      
// 如果条件满足,则执行!
      if(fn()) {
        callback();
      }
      
// 如果条件不满足,但并未超时,再来一次
      else if (Number(new Date()) < endTime) {
        setTimeout(p, interval);
      }
      
// 不匹配且时间消耗过长,则拒绝!
      else {
        errback(new Error(&#39;timed out for &#39; + fn + &#39;: &#39; + arguments));
      }
  })();
}
 
// 用法:确保元素可见
poll(
  function() {
    return document.getElementById(&#39;lightbox&#39;).offsetWidth > 0;
  },
  function() {
    
// 执行,成功的回调函数
  },
  function() {
    
// 错误,失败的回调函数
  }
);
Copy after login

Polling has been used in the web for a long time and will still be used in the future.

once

Sometimes, you want a given function to occur only once, similar to the onload event. The code below provides the functionality you are talking about:

function once(fn, context) { 
  var result;
 
  return function() { 
    if(fn) {
      result = fn.apply(context || this, arguments);
      fn = null;
    }
 
    return result;
  };
}
 
// 用法
var canOnlyFireOnce = once(function() {
  console.log(&#39;Fired!&#39;);
});
 
canOnlyFireOnce(); 
// "Fired!"
canOnlyFireOnce(); 
// nada 
          
// 没有执行指定函数
Copy after login

once functions ensure that a given function can only be called once, thus preventing repeated initialization!

The above is the detailed content of Detailed explanation of the usage of basic JavaScript functions debounce, poll and once instances. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!