schwarz

archive of mindset

schwarz header image 5

Javascript: Sleep, keypress delays and bashing bad articles

October 21, 2007 · 0 comments

Today I read the high scalability article aimed to reduce the amount of requests to your server by not sending XMLHttpRequests for every keystroke.

It was suggested that a onblur event was used to measure when the user had stopped typing.

Will your users expect to have to tab out of a field before something else happens? Will it confuse them if they've started typing in another text area? Probably.

At work, I'd whipped up something elegant to handle this very same paradigm for validating or searching user input.

Example

(using jquery to make those events really easy)


$('input.search').keyup(function () {
	// Lets have a clean version of the search string, you could really do more there though
	var search_term = new RegExp(this.value.replace(/\\/g, ''), "i");
	var search_execution = function () {
		// Expensive server queries here - buy some real servers guys! (what on earth are you requesting?)
	}.sleep(175);
});

175 milliseconds delay before the method is executed is a good typing rate. Maybe you want to change this to something that you're more comfortable with though.

Hold on, last time I checked, sleep() wasn't a part of the standard JavaScript language. Rather than using a simple setTimeout(), I decided that the ajax'd method shouldn't be executed again until it had finished the last time it ran.

The sleep method


Function.prototype.sleep = function (millisecond_delay) {
	if(window.sleep_delay != undefined) clearTimeout(window.sleep_delay);
	var function_object = this;
	window.sleep_delay = setTimeout(function_object, millisecond_delay);
};

er, yeah.. thats about it. I just really wanted to post the sleep method. I'd written it over a year ago now, but it's still used on a pretty regular basis. I use it for searching conducted in the DOM by hiding elements that don't match a simple regex.

→ 0 comments Tags: