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

Introduction to the basic implementation methods of throttle valve and debouncing

不言
Release: 2019-04-13 11:53:00
forward
2184 people have browsed it

This article brings you an introduction to the basic implementation methods of throttle valve and debouncing. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Throttle valvethrottle

The events triggered are executed in a periodic manner, not in real time. Like a dripping faucet.

function throttle (fn, delay) {
  // 利用闭包变量时效性
  let timeout
  let arg
  return function () {
    arg = arguments
    if (!timeout) {
      timeout = setTimeout(() => {
        fn.apply(this, arg)
        timeout = null
      }, delay)
    }
  }
}
// demo
/*
var test = throttle(function (a) {console.log(a)}, 1000)
test(1) // 不执行
test(2) // 不执行
test(3)
=> 3
test = null // 不需要时释放内存
*/
Copy after login

Debounce debounce

Triggers N milliseconds after the last event, such as an elevator door.

function debounce (fn, delay){
  let timeout
  return function(){
    const args = arguments
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}
// 用法同throttle
Copy after login

The above is the detailed content of Introduction to the basic implementation methods of throttle valve and debouncing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
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!