JSFiddle - React, Tailwind, and code Playground

by dumptyd

HTML

<div>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae deserunt cum eum sint alias ipsam eligendi dolor molestias! Velit, provident.
</div>

CSS

div {
  width: 400px;
  height: 400px;
  border: 1px solid;
  margin: 1rem auto;
}

JavaScript

const debounce = (func, ms) => {
	if (!ms) return func;

	let lastCalledAt = null;
  let timer = null;

	const ret = function(...args) {
  	clearTimeout(timer);
  	const currentCalledAt = Date.now();
    if (lastCalledAt === null ||  lastCalledAt + ms > currentCalledAt) {
    	lastCalledAt = currentCalledAt;
      timer = setTimeout(ret, ms);
      return;
    }
    lastCalledAt = currentCalledAt;
    return func(...args);
  };
  return ret;
};

document.querySelector('div').addEventListener('click', debounce(function() {
	console.log('called at: ', Date.now());
}, 3000));