簡體   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