Skip to content

Instantly share code, notes, and snippets.

@prantomollick
Created January 19, 2025 14:57
Show Gist options
  • Save prantomollick/042e4278e88622384f10be6f8e111e0f to your computer and use it in GitHub Desktop.
Save prantomollick/042e4278e88622384f10be6f8e111e0f to your computer and use it in GitHub Desktop.
javascript-debounce-function-on-input-ajax-request
function debounce(func, wait, immediate) {
let timeout;
return function () {
const context = this;
const args = arguments;
const later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
function deleteProduct() {
const productsTable = document.getElementById("c-products-table");
const productDeleteForm = document.getElementById("c-delete-product-form");
if (!productsTable || !productDeleteForm) {
return;
}
const handleDeleteProduct = function (e, productId) {
e.preventDefault();
let actionUrl = getCurrentActionUrl(productId);
const actionForm = e.target;
actionForm.action = actionUrl;
actionForm.submit();
};
productsTable.addEventListener("click", function (e) {
const productDeleteBtn = e.target.closest("#c-product-delete-btn");
if (productDeleteBtn) {
e.preventDefault();
const productId = productDeleteBtn.dataset.productId;
if (!productId) {
return;
}
productDeleteForm.addEventListener("submit", (e) =>
handleDeleteProduct(e, productId)
);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment