設置鎖變量,請求發出前檢查並加鎖,完成後解鎖;同時禁用按鈕防止用戶瘋狂點擊。
let isRequesting = false;
$('#likeBtn').on('click', function() {
if (isRequesting) return;
const $btn = $(this).prop('disabled', true);
isRequesting = true;
$.ajax({
url: '/api/like',
method: 'POST',
data: { id: 123 }
}).done(() => {
// 更新 UI
}).fail(() => {
alert('操作失敗');
}).always(() => {
isRequesting = false;
$btn.prop('disabled', false);
});
});若允許合併短時間內多次點擊為一次請求,可用 `lodash.debounce` 或手動 `setTimeout` 實現節流。