2017-05-24 59 views
0

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

+4

这也许应该已经在链接的线程回答的评论来实现。而不是一个新的问题。 – Turnip

+0

它说它在源代码链接在这个问题 - *如果通过'立即',触发功能的前沿,而不是尾随* ..所以,我猜如果你提供两个,那么函数是在后边缘触发 –

+0

不,它必须是一个新问题 - 因为Stack Overflow不允许我发表任何评论... ;-) –

回答

0

我给你做了一个小例子。我希望你能理解在给定的文章中描述的方式和原理。

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

您可以更详细地here看到这一点,它在下面的特定职位的答案一个媒体链接。

0

一个基本的反跳可以像下面

var buttonEl = document.querySelector("button"); 
 
var countryEl = document.querySelector("#counter"); 
 
var counter = 0; 
 

 
buttonEl.addEventListener("click", debounce(onClick, 1000)); 
 

 
function debounce(cb, delay){ 
 
\t var lastCallTime = new Date().getTime(); 
 
    return function(){ 
 
    \t if((new Date().getTime() - lastCallTime) > delay){ 
 
    \t lastCallTime = new Date().getTime(); 
 
    \t \t cb.call(this, arguments); 
 
    } 
 
    } 
 
} 
 

 

 
function onClick(event){ 
 
\t //console.log(this, event); 
 
    countryEl.innerHTML = counter++; 
 
}
<button> 
 
Click Me!! 
 
</button> 
 

 
<div id="counter"> 
 
    
 
</div>

相关问题