Understanding Debounce

by Suman Kumar

HTML

<input id="one" type="text" placeholder="Enter val">

JavaScript

function _debounce(cb, delay) {
	let lastFunc;
  
	return function() {
  	const _this = this;
    const args = arguments;
    
    if(lastFunc)
  		clearTimeout(lastFunc);
    
    lastFunc = setTimeout(function() {
      cb.apply(_this, args);
    },delay);
  }
}

document.getElementById('one')
.addEventListener('keyup', _debounce(function(event){
	console.log(event.target.value);
}, 2000));