繁体   English   中英

JavaScript去抖功能,为什么只有两个参数?

[英]JavaScript debounce function, why only two arguments?

解释JavaScript去抖函数的后续问题为什么如何调用去抖函数的例子只提供两个参数? (去抖功能有三个参数。)

我为你做了一个例子。 我希望你理解它在给定的帖子中如何以及为什么工作。

 function debounce(func, wait, immediate){ var timeout; //create timeout for the given "func"tion return function() { var context = this, args = arguments; var later = function() { timeout = null; //clear/reset the timeout if (!immediate) func.apply(context, args); //call function if immediate is "false" or "null/undefined" }; var callNow = immediate && !timeout; //full if statement below //if((immediate != null || immediate == true) && (timeout == null || timeout == false)) //callNow = true; clearTimeout(timeout); //clear the last timeout timeout = setTimeout(later, wait); //call function "later" after "wait"-time if (callNow) func.apply(context, args); //call function immediately (if-statement above) }; }; var timeout; function example(variable, wait, now){ var callNow = now && !timeout; if(callNow) { console.log(variable); } else { var logVar = function(){ timeout = null; console.log(variable); }; timeout = setTimeout(logVar, wait); } }; example("Hello World immediate", 2000, true); //immediate example("Hello World after two seconds!", 2000); //after "wait"-time example("Hello World immediate", 2000, true); //after "wait"-time, because there is a timeout allready 

你可以在这里更详细地看到这一点 ,它已经在给定帖子下面的一个答案中。

基本的去抖动可以像下面这样实现

 var buttonEl = document.querySelector("button"); var countryEl = document.querySelector("#counter"); var counter = 0; buttonEl.addEventListener("click", debounce(onClick, 1000)); function debounce(cb, delay){ var lastCallTime = new Date().getTime(); return function(){ if( (new Date().getTime() - lastCallTime) > delay){ lastCallTime = new Date().getTime(); cb.call(this, arguments); } } } function onClick(event){ //console.log(this, event); countryEl.innerHTML = counter++; } 
 <button> Click Me!! </button> <div id="counter"> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM