Created
January 19, 2025 14:57
-
-
Save prantomollick/042e4278e88622384f10be6f8e111e0f to your computer and use it in GitHub Desktop.
javascript-debounce-function-on-input-ajax-request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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