debounce and throttle

by Anchit Gupta

HTML

<div>

</div>

JavaScript

// debouncing example

let counter = 0;

const getData = () => {
	console.log("Getting Data Debounce: ", counter++);
}

const getDebounceData = (func, limit) => {
	let timer;
  return function(){
  	let context = this,
    		args = arguments;
  	clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(context, args);
    }, limit);
  }
}

getDebounceData(getData, 300);

// throttling example

let counter1 = 0;

const getData1 = () => {
	console.log("Getting Data Throttle: ", counter1++);
}

const getThrottleData = (func, limit) => {
	let flag = true;
  return function(){
  	let timer,
    		context = this,
    		args = arguments;
    if (flag){
    	func.apply(context, args);
      flag = false;
      setTimeout(() => {
      	flag = true;
      }, limit);
    }
  }
}

getThrottleData(getData1, 500);