Skip to content

Instantly share code, notes, and snippets.

@isalmanhaider
Created March 26, 2024 08:24
Show Gist options
  • Save isalmanhaider/359316466a37ecf90f366c3d4d845833 to your computer and use it in GitHub Desktop.
Save isalmanhaider/359316466a37ecf90f366c3d4d845833 to your computer and use it in GitHub Desktop.
JS debounce
let debounce = function (cb, delay) {
let timer;
return function () {
let context = this;
clearTimeout(timer);
timer = setTimeout(() => {
cb.apply(context, arguments);
}, delay);
};
};
@isalmanhaider
Copy link
Author

let inputEle = document.getElementById("inputElement");
let username = document.getElementById("username");

let generateUsername = (e) => {
  username.innerHTML = e.target.value.split(" ").join("-");
};
let debounce = function (cb, delay) {
  let timer;
  return function () {
    let context = this;
    clearTimeout(timer);
    timer = setTimeout(() => {
      cb.apply(context, arguments);
    }, delay);
  };
};

inputEle.addEventListener("keyup", debounce(generateUsername, 1000));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment