我想使用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)