Javascript函数限制

CL9*_*L90 5 javascript throttling

我想使用JS Throttle.但我正在努力让它正常工作.

我尝试了本文中的代码:https: //codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf

但Throttle不能按预期工作,因为每次我点击按钮,一个"|" 添加到div.没有点击被丢弃.

哪里是错误的?

function foo() {
	$("#respond").append("|");
}

const throttle = (func, limit) => {
  let inThrottle
  return function() {
    const args = arguments
    const context = this
    if (!inThrottle) {
      func.apply(context, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

var onClick = function() {
    throttle(foo(), 50000);
};

$('#button').click(onClick);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="button" value="Click Me" />
<div id="respond"></div>
Run Code Online (Sandbox Code Playgroud)

Arm*_*ran 5

为了throttle(func, limit)工作-产品只能有一个实例。

问题在于onClick示例中的函数每次调用都会创建一个新实例。

这将使基础inThrottle变量变得毫无意义,因为每次点击都会创建一个新副本。

解决方案是将一个实例throttle(foo, 50000)直接称为产品。

另外,foo本身应该被传递(而不是其产品)。

请参阅下面的实际示例,以及有关更多信息的闭包范围

// Foo.
const foo = (...args) => {
  $("#respond").append("|");
}

// Throttle.
const throttle = (func, limit) => {
  let inThrottle
  return (...args) => {
    if (!inThrottle) {
      func(...args)
      inThrottle = setTimeout(() => inThrottle = false, limit)
    }
  }
}

// On Click.
const onClick = throttle(foo, 1000)

// Button - Click.
$('#button').click(onClick);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="button" value="Click Me" />
<div id="respond"></div>
Run Code Online (Sandbox Code Playgroud)