Debounce & Throttle

by ananyaneogi

CSS

body {
  height: 99999px;
}

JavaScript

function debounce(fn, delay) {
  // maintain a timer
  let timer = null;
  // closure function that has access to timer
  return function() {
    // get the scope and parameters of the function
    // via 'this' and 'arguments'
    let _this = this;
    let args = arguments;
    // if event is called, clear the timer and start over
    clearTimeout(timer);
    timer = setTimeout(function() {
      fn.apply(_this, args);
    }, delay);
  }
}

const throttle = (callback, delay) => {
  let hold = false

  return function handleEvent (...args) {
    if (hold) return

    hold = true
    callback.apply(this, args)

    setTimeout(() => {
      hold = false
    }, delay)
  }
}

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}


function doSomethingOnScroll() {
	console.log('scrolling', Date.now());
  document.body.style.backgroundColor = getRandomColor();
}

document.addEventListener('scroll', debounce(doSomethingOnScroll, 20));
/* document.addEventListener('scroll', throttle(doSomethingOnScroll, 200)) */