JSFiddle - React, Tailwind, and code Playground

by azlar chen

HTML

<div class='p' id='p'>
  <div id='c'></div>
</div>

CSS

div.p {
  height: 10000px;
  width: 10000px;
}

#c {
  background-color: rgba(0, 0, 255, .5);
  position: absolute;
  top: 0;
  left: 0;
  width: 20px;
  height: 20px;
}

JavaScript

let i = 0;
let c = document.getElementById('c');
/* document.body.addEventListener('mousemove', throttle(move, 100)); */


document.body.addEventListener('click', debounce(move, 500, {
  leading: true
}));

function move() {
  c.style.top = ((parseInt(c.style.top) || 0) + 5) + 'px';
  c.style.left = ((parseInt(c.style.left) || 0) + 5) + 'px';
}

function debounce(fn, time = 100, options = {}) {
  let args = Array.prototype.slice.call(arguments);
  let timeout = null;
  let debouncing = false;

  let {
    leading
  } = options;
  
  return function() {

    if (leading) {
    	console.log('x', timeout);
      if (!timeout && !debouncing) {
        fn.apply(this, args);
        debouncing = true;

        setTimeout(() => {
          debouncing = false;
          leading = false;
          
          timeout = setTimeout(() => {
            leading = true;
            debouncing = false;
            timeout = null;
          }, time);
        }, time);
      }
    } else {
      	clearTimeout(timeout);
        timeout = setTimeout(() => {
          console.log('xxx', debouncing);
          debouncing = false;
          timeout = null;
          fn.apply(this, args);
          
          leading = true;

        }, time);
    
    }
  }

}

function throttle(fn, freq = 33.33333) {
  let args = Array.prototype.slice.call(arguments);

  let processing = false;
  return function() {
    if (!processing) {
      processing = true;

      setTimeout(() => {
        fn.apply(this, args);
        processing = false;
      }, freq);
    }
  }
};