diff --git a/app/assets/javascripts/updateStatus.js b/app/assets/javascripts/updateStatus.js index 071c622e0..a4a06b03b 100644 --- a/app/assets/javascripts/updateStatus.js +++ b/app/assets/javascripts/updateStatus.js @@ -3,10 +3,40 @@ window.GOVUK.Modules.UpdateStatus = function() { - let getRenderer = $component => response => $component.html( + const getRenderer = $component => response => $component.html( response.html ); + const throttle = (func, limit) => { + + let throttleOn = false; + let callsHaveBeenThrottled = false; + let timeout; + + return function() { + + const args = arguments; + const context = this; + + if (throttleOn) { + callsHaveBeenThrottled = true; + } else { + func.apply(context, args); + throttleOn = true; + } + + clearTimeout(timeout); + + timeout = setTimeout(() => { + throttleOn = false; + if (callsHaveBeenThrottled) func.apply(context, args); + callsHaveBeenThrottled = false; + }, limit); + + }; + + }; + this.start = component => { let id = 'update-status'; @@ -19,7 +49,7 @@ this.$textbox .attr('aria-described-by', this.$textbox.attr('aria-described-by') + ' ' + id) - .on('input', this.update) + .on('input', throttle(this.update, 150)) .trigger('input'); }; diff --git a/tests/javascripts/updateStatus.test.js b/tests/javascripts/updateStatus.test.js index 35fb360b1..ae0fa5b24 100644 --- a/tests/javascripts/updateStatus.test.js +++ b/tests/javascripts/updateStatus.test.js @@ -127,10 +127,38 @@ describe('Update content', () => { window.GOVUK.modules.start(); expect($.ajax.mock.calls.length).toEqual(1); + // 150ms of inactivity + jest.advanceTimersByTime(150); helpers.triggerEvent(textarea, 'input'); expect($.ajax.mock.calls.length).toEqual(2); }); + test("It should fire only after 150ms of inactivity", () => { + + let textarea = document.getElementById('template_content'); + + // Initial update triggered + window.GOVUK.modules.start(); + expect($.ajax.mock.calls.length).toEqual(1); + + helpers.triggerEvent(textarea, 'input'); + jest.advanceTimersByTime(149); + expect($.ajax.mock.calls.length).toEqual(1); + + helpers.triggerEvent(textarea, 'input'); + jest.advanceTimersByTime(149); + expect($.ajax.mock.calls.length).toEqual(1); + + helpers.triggerEvent(textarea, 'input'); + jest.advanceTimersByTime(149); + expect($.ajax.mock.calls.length).toEqual(1); + + // > 150ms of inactivity + jest.advanceTimersByTime(1); + expect($.ajax.mock.calls.length).toEqual(2); + + }); + });