3 ms·
I am doing validation for username and email from JavaScript with the server similar to the way twitter is doing. I have to make sure that I do not bombard my s
by mandeepj 14y ago
I am doing validation for username and email from JavaScript with the server similar to the way twitter is doing. I have to make sure that I do not bombard my server for each keystroke and mouse click (in case user decides to copy+paste the email address using the mouse). This is how I did. It works so far but as always it can enhanced. I can share the full source but it is the skeleton to give u the idea. In essence I am waiting for 1300 milliseconds before hitting the server again.
$(emailTextBoxId).keyup(function (event) {
//executes a function, once, after waiting a specified number of milliseconds
setTimeout("CheckEmailAddressAvailability()", 1300);
//stopping bubble
return false;
});
$(emailTextBoxId).keydown(function (event) {
safeToPerformEmailCheck = true;
document.getElementById("ValidEmailAdd").style.display = "none";
document.getElementById("ExistingEmailAcc").style.display = "none";
//document.getElementById("InvalidEmailAdd").style.display = "none";
});
$(emailTextBoxId).mouseup(function (event) {
safeToPerformEmailCheck = true;
CheckEmailAddressAvailability();
});
Edit:
I just saw the examples posted by fellow readers at following links are much better than mine. I am glad I really learned some good stuff today and I will edit my code today as first thing once I go home this eve. Really neat.
http://jsbin.com/ejimok/3/edit http://jsbin.com/ejimok/3/edit
http://jsbin.com/ejimok/5/edit http://jsbin.com/ejimok/5/edit
- napillo 14y agoThat's how I do my keypress events. It stores the keypress into a buffer, then only calls the 'search' when a timeout is hit. Calling setTimeout gives you a pointer to the timer, so you can clear the timeout when you get another keypress, thus allowing you to start the timer again. If I tried to send on every keypress, I'd occasionally get out of order packets. Sending them buffered up all at once lets me avoid out of sequence packets, and it reduces the load on the server.