Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  77] [ 1]  / answers: 1 / hits: 68793  / 13 Years ago, fri, october 21, 2011, 12:00:00

On my website I use JavaScript/AJAX to do the search and show results while the user is still typing.



HTML (body):



<form action= method=post accept-charset=utf-8>
<p><input type=text name=q id=q value= onkeyup=doSearch(this.value) /></p>
</form>


JavaScript (header):



function doSearch(text) {
// do the ajax stuff here
// call getResults.php?search=[text]
}


But this could cause a lot of requests coming to the server.



Thus I want to relieve the server by setting up a delay:



Whenever the onkeyup event is fired, the function doSearch() should show an ajax loading graphic and wait for 2 seconds. Only if the event is NOT fired again during these 2 seconds, the results should be fetched from the PHP file.



Is there any way to do this? Could you help me please? Thanks in advance!


More From » ajax

 Answers
6
var delayTimer;
function doSearch(text) {
clearTimeout(delayTimer);
delayTimer = setTimeout(function() {
// Do the ajax stuff
}, 1000); // Will do the ajax stuff after 1000 ms, or 1 s
}

[#89501] Wednesday, October 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marquezb

Total Points: 237
Total Questions: 97
Total Answers: 89

Location: Israel
Member since Wed, Apr 14, 2021
3 Years ago
;