Archive for December 27th, 2013

Prism is fast, generally fast enough to use for a live syntax highlighter. But for large texts (multiple kilocharacters) having the text re-highlighted with every input bogs down, and I can type faster than the text can show up. I remember old word processors that were like that, back in the dark ages of computerdom. But it's unacceptable today.

What I need to do is "debounce" the input events, so they aren't piling up and creating a backlog of highlighting that is going to be redone with the next event anyway. John Hann has a nice little routine that I simplified into:

function debounce (func, threshold){
	if (!threshold) return func; // no debouncing
	var timeout;
	return function(){
		var self = this, args = arguments;
		clearTimeout(timeout);
		timeout = setTimeout(function(){
			func.apply(self, args);
		}, threshold);
	};
}

Basically, it uses setTimeout to delay the application of the function, and resets the timer every time it's called. Use it as var debouncedFunc = debounce(func, 100);