From 5eea27004c332dc1fc9ab6b583b5a21b4408b6b2 Mon Sep 17 00:00:00 2001 From: Alex Yatskov Date: Tue, 3 May 2016 20:49:09 -0700 Subject: [PATCH] Optimization --- ext/bg/js/yomichan.js | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/ext/bg/js/yomichan.js b/ext/bg/js/yomichan.js index e6d0acc4..bc0f3a87 100644 --- a/ext/bg/js/yomichan.js +++ b/ext/bg/js/yomichan.js @@ -34,6 +34,8 @@ class Yomichan { }); this.translator = new Translator(); + this.xhr = null; + this.updateState('disabled'); loadOptions((opts) => { @@ -123,16 +125,26 @@ class Yomichan { } callAnkiApi(action, data, callback) { - if (this.options.enableAnkiConnect) { - const xhr = new XMLHttpRequest(); - xhr.addEventListener('loadend', () => callback(xhr.responseText ? JSON.parse(xhr.responseText) : null)); - xhr.open('POST', 'http://127.0.0.1:8888'); - xhr.withCredentials = true; - xhr.setRequestHeader('Content-Type', 'text/json'); - xhr.send(JSON.stringify({action: action, data: data})); - } else { + if (!this.options.enableAnkiConnect) { callback(null); + return; } + + if (this.xhr !== null) { + this.xhr.abort(); + } + + this.xhr = new XMLHttpRequest(); + this.xhr.addEventListener('loadend', () => { + const resp = this.xhr.responseText; + callback(resp ? JSON.parse(resp) : null); + this.xhr = null; + }); + + this.xhr.open('POST', 'http://127.0.0.1:8888'); + this.xhr.withCredentials = true; + this.xhr.setRequestHeader('Content-Type', 'text/json'); + this.xhr.send(JSON.stringify({action: action, data: data})); } static notifyChange(name, value) {