Skip to content

Commit 80c8cfc

Browse files
committed
instantsearch.js: Add idle timer on input changes.
Avoid filling the browser history for every letter.
1 parent efd1a29 commit 80c8cfc

File tree

1 file changed

+27
-7
lines changed

1 file changed

+27
-7
lines changed

docs/js/instantsearch.js

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,19 +20,39 @@
2020
},
2121
});
2222

23-
doc.getElementById('searchbox').addEventListener('keyup', function (event) {
23+
getNextSearchURL = () => {
24+
const searchInputElements = document.getElementsByClassName('ais-SearchBox-input');
25+
const text = searchInputElements[0].value.trim();
26+
const selectedPaginationItemElements = doc.getElementsByClassName('ais-Pagination-item--selected');
27+
const page = selectedPaginationItemElements.length ? parseInt(selectedPaginationItemElements[0].innerText) : 1
2428
const url = new URL(window.location);
25-
url.searchParams.set('sq', event.target.value.trim());
26-
if (url.href != window.location.href) {
27-
url.searchParams.set('p', 1);
29+
url.searchParams.set('sq', text);
30+
url.searchParams.set('p', page);
31+
return url;
32+
};
33+
34+
let idleTimer;
35+
const startIdleTimer = (url) => {
36+
stopIdleTimer();
37+
idleTimer = window.setTimeout(()=>{
2838
window.history.pushState({}, '', url);
39+
}, 1500);
40+
};
41+
const stopIdleTimer = () => {
42+
window.clearTimeout(idleTimer);
43+
}
44+
45+
doc.getElementById('searchbox').addEventListener('keyup', function (event) {
46+
const url = getNextSearchURL();
47+
if (url.searchParams.get('sq') != (new URL(window.location)).searchParams.get('sq')) {
48+
url.searchParams.set('p', 1);
49+
startIdleTimer(url);
2950
}
3051
})
3152

3253
doc.getElementById('pagination').addEventListener('click', function (event) {
33-
const page = doc.getElementsByClassName('ais-Pagination-item--selected').length ? parseInt(doc.getElementsByClassName('ais-Pagination-item--selected')[0].innerText) : 1
34-
const url = new URL(window.location);
35-
url.searchParams.set('p', page);
54+
stopIdleTimer();
55+
const url = getNextSearchURL();
3656
window.history.pushState({}, '', url);
3757
})
3858

0 commit comments

Comments
 (0)