From e6fc50e01f819f060229fd845160a664ece4e06a Mon Sep 17 00:00:00 2001 From: Alex Liebowitz Date: Fri, 11 Nov 2016 09:22:53 -0500 Subject: [PATCH] Tweak logic for handling failed connections in lbry.jsonrpc_call() - Move AJAX error callback declaration to the right spot (before, it was inside the load callback) - Add support for custom timeouts --- js/lbry.js | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/js/lbry.js b/js/lbry.js index eec987bed..bf57e6c05 100644 --- a/js/lbry.js +++ b/js/lbry.js @@ -10,8 +10,20 @@ var lbry = { } }; -lbry.jsonrpc_call = function (connectionString, method, params, callback, errorCallback, connectFailedCallback) { +lbry.jsonrpc_call = function (connectionString, method, params, callback, errorCallback, connectFailedCallback, timeout) { var xhr = new XMLHttpRequest; + if (typeof connectFailedCallback !== 'undefined') { + if (timeout) { + xhr.timeout = timeout; + } + + xhr.addEventListener('error', function (e) { + connectFailedCallback(e); + }); + xhr.addEventListener('timeout', function() { + connectFailedCallback(new Error('XMLHttpRequest connection timed out')); + }) + } xhr.addEventListener('load', function() { var response = JSON.parse(xhr.responseText); @@ -24,12 +36,6 @@ lbry.jsonrpc_call = function (connectionString, method, params, callback, errorC } }); - if (connectFailedCallback) { - xhr.addEventListener('error', function (e) { - connectFailedCallback(e); - }); - } - xhr.open('POST', connectionString, true); xhr.send(JSON.stringify({ 'jsonrpc': '2.0',