JS anti shake and function throttling annotation version

Time:2020-2-25

My understanding of anti shake and function throttling in my study, the following notes may be more verbose or difficult to understand.

// anti shake  
Function noshake (FN, time) {// closure, which can be understood as a function of an inner function referencing a variable in the scope of an outer function. The inner function must be a function.  
  Var shake = null; // the closure declares variables for the inner function. There is a significant difference between anti shake and throttling.  
  return function () {  
  console.log(shake);  
  If (shake) {// judge whether shake is true or false (null or setTimeout). Clear timer if true  
  clearTimeout(shake);  
 }// repeat: if this method is called repeatedly in time, clear the timer, and the following code will reassign the timer.  
  //Re: it can be understood that no matter how many times I click in time, the timer will be executed after I stop clicking.  
  Shake = setTimeout (function() {// whatever the value of shake is, the timer will be assigned again here  
  Console.log (this); // the current this points to window  
  FN. Apply (this, arguments); // change this point of FN to prevent this from being changed in the inner function call FN.  
  Shake = null; // clear shake after execution  
  }, time)  
 }}  
function fn() { // anti shake执行函数  
  Console. Log ('I am anti shake ');  
}  
Var FN1 = noshake (FN, 1000); // call noshake to return the inner function  
$('. ABC'). On ('click ', function() {// event triggered  
  fn1()  
})  
//Function throttling  
function throttle(fn, time) {  
  Var status = false; // this is different from anti shake  
  return function () {  
  //Heavy: the biggest difference between throttling and anti shake is that anti shake clears the timer, but throttling does not, and the timer is still executing.  
  //The status changes to false only after the timer is executed in time. If the call is repeated within time, the function execution will exit until the last timer execution is completed.  
  if (status) {   
 return false;  
 }  status = true;  
  setTimeout(function () {  
  fn.apply(this, arguments);  
  status = false;  
 }, time)  
 }}// function calls are not repeated here, just like anti shake.

Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]