Created
October 20, 2023 16:23
-
-
Save susilolab/34a5a72d952ce82c9fd3b1e29540124b to your computer and use it in GitHub Desktop.
Ajax timeout dengan jQuery
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
'use strict' | |
function fetchTimeout(url, timeout, {signal, ...options} = {}) { | |
function createJqueryAjaxAbortAdapter(signal) { | |
return function(jqXhr) { | |
signal.addEventListener("abort", () => { | |
jqXhr.abort(); | |
}); | |
}; | |
} | |
const ctrl = new AbortController() | |
const ajaxReq = (url, ctrl, options) => { | |
return $.ajax({ | |
beforeSend: createJqueryAjaxAbortAdapter(ctrl.signal), | |
method: options.method || 'GET', | |
url: url | |
}) | |
} | |
const promise = ajaxReq(url, ctrl, {}) | |
setTimeout(() => ctrl.abort(), timeout) | |
return promise | |
} | |
// Contoh penggunaan | |
fetchTimeout('https://example.com/long-run', 6000, {}) | |
.done(resp => console.log(resp)) | |
.fail(err => console.log(err)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment