From 7ab95ba2110d7818e9a6529a77cab111f5016da6 Mon Sep 17 00:00:00 2001 From: Samuel Young Date: Thu, 11 Sep 2025 15:41:19 +0100 Subject: [PATCH] CLDC-4066: Implement a debounce on address search disappointingly the underlying library https://github.com/alphagov/accessible-autocomplete doesn't have this as an option, though we can implement one ourselves in the fetch code --- .../controllers/address_search_controller.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/frontend/controllers/address_search_controller.js b/app/frontend/controllers/address_search_controller.js index de54090ec..833bc317f 100644 --- a/app/frontend/controllers/address_search_controller.js +++ b/app/frontend/controllers/address_search_controller.js @@ -4,10 +4,28 @@ import 'accessible-autocomplete/dist/accessible-autocomplete.min.css' const options = [] +let latestQueryId = 0; + +const sleep = (ms) => { + return new Promise(resolve => setTimeout(resolve, ms)); +} + const fetchOptions = async (query, searchUrl) => { if (query.length < 2) { throw new Error('Query must be at least 2 characters long.') } + + // implement a debounce + // this is because this API has periods of high latency if OS Places has an outage + // making too many requests can overwhelm the number of threads available on the server + // which can in turn cause a site wide outage + latestQueryId++; + const myQueryId = latestQueryId; + await sleep(500); + if (myQueryId !== latestQueryId) { + throw new Error('Outdated query, ignoring result.'); + } + try { const response = await fetch(`${searchUrl}?query=${encodeURIComponent(query.trim())}`) return await response.json()