JSFiddle - React, Tailwind, and code Playground

by khushboo097

HTML

<input id="txt" />

JavaScript

function debounce(cb, delay) {
  let timerId = null

  return function (...args) {
    	clearTimeout(timerId);
      timerId = setTimeout(() => {
        timerId = null
        return cb(...args)
      }, delay)
    }
    console.log('didnt call')
}

function throttle(cb, delay) {
	let initTime = 0;
  
  return function(...args) {
  	const now = Date.now();
    
    if (now - initTime >= delay) {
    	initTime = now;
    	return cb(...args);
    }
  }
  
}

function logMessage(message) {
  console.log(message);
}

const throttledLog = throttle(logMessage, 2000);

throttledLog('First call'); // Logs immediately (since this is the first call)
throttledLog('Second call'); // Ignored, since it's within 2000ms of the first call
setTimeout(() => throttledLog('Third call'), 2500); // 
const search = (val) => {
	console.log('searching.. ', val);
}
const debounced = debounce(search, 2000);
const throttled = throttle(search, 2000);
const inp = document.getElementById('txt');
inp.addEventListener('input', (e) => throttled(e.target.value));