UNPKG

x-http-client

Version:

An http client to simplify sending requests (HTTP & JSONP) in the browser.

37 lines (32 loc) 1.04 kB
/** * Add timeout event listener on the XHR object. * * @param {XMLHttpRequest} xhr The XHR to add timeout event listener. * @param {number} timeout The time to wait in milliseconds. * @param {() => void} listener The timeout callback. * @returns {() => void)} Returns a function to remove the timeout event listener. */ function addTimeoutListener(xhr, timeout, listener) { var timeoutId = null; var supportTimeout = 'timeout' in xhr && 'ontimeout' in xhr; if (supportTimeout) { xhr.timeout = timeout; xhr.ontimeout = listener; } else { timeoutId = setTimeout(listener, timeout); } // Call this function to remove timeout event listener function clearTimeoutEvent() { if (xhr) { if (timeoutId === null) { xhr.ontimeout = null; } else { clearTimeout(timeoutId); } xhr = null; listener = null; } } return clearTimeoutEvent; } module.exports = addTimeoutListener;