Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AJAX request handler 1

Status
Not open for further replies.

JBellTek

Programmer
Jun 11, 2009
29
US
I am writing a script that hits against the server on keyup to populate a list, but I want to write something to keep the server from getting flooded as they are typing

My thought was to write a handler that would start a global variable countdown and send the request when the counter hit 0, with each subsequent keystroke resetting the counter. That way rapid keystrokes would not all be processed if the user was still typing or a scan gun was used, and only one AJAX request would be sent.

I have been working on this all week. I thought that this would be a common issue. Either I am missing something obvious, or I don't know the keywords to use in searching. If anyone could offer a suggestion, or better yet point me to a tutorial where this kind of thing is done, I would greatly appreciate it.
 
You probably want to use the setTimeout and clearTimeout commands. This pseudo-code should give you the general idea, and you can ask in forum216 if you get stuck with the JS:

- initialise a timer handle to be null
- onkeypress (1) if the timer handle is not null, clear it using clearTimeout and set it back to null
- onkeypress (2) set a timer going and store the handle in your variable

I'd say something like 500 ms would be a good time, although you can tweak this.

When the timer fires you know you can fire your AJAX request.

Hope this helps,
Dan

Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
BillyRay:
Thank you for your input.

My final code:
Code:
var scnTime;
$(document).ready(function(){
 $("#scanned").focus();

 $("#scanned").keyup(function(){
	 clearTimeout(scnTime);
	 scnTime = setTimeout("loadContent()", 500);
  });
});

It turns out what I was missing was the global declaration of var scnTime.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top