Skip to content

Instantly share code, notes, and snippets.

@gre
Created August 1, 2011 17:39
Show Gist options
  • Select an option

  • Save gre/1118605 to your computer and use it in GitHub Desktop.

Select an option

Save gre/1118605 to your computer and use it in GitHub Desktop.
RealTime.js - update system for building ajax stuff like autocompletes
/**
* RealTime.js : Update system
* Manage input (or textarea) smart callback on change
* @author Gaetan Renaudeau <[email protected]>, Namolovan Nicolae <[email protected]>
*/
var RealTime = function(node, o) {
var self = this;
this.input = node;
var getTime = function() {
return new Date().getTime();
}
self.callback = o['update'] || function(){};
self.textChange = o['textChange'] || function(){};
self.timer = false;
self.lastCall = getTime();
self.lastSearch = self.input.value;
self.minInterval = o['minInterval'] || 800; // min interval between each call to minimize requests
self.maxInterval = o['maxInterval'] || 800; // max interval, to allow some updates
self.minTextLength = o['minTextLength'] || 0;
if (self.minInterval > self.maxInterval) self.maxInterval = self.minInterval + 100;
// first couch
this.onKeyup = function(e) {
if (self.timer === false) {
self.lastCall = getTime();
self.timerStarted = getTime();
self.ignoredKeys = 0;
self.onInputChange();
}
else {
if ( /* maxInterval */ (getTime() - self.timerStarted) > self.maxInterval ) {
clearTimeout(self.timer); // Don't need the timer anymore
self.timer = false;
self.lastCall = self.timerStarted; // Force to execute the update code
self.onInputChange();
}
else {
self.lastCall = getTime();
}
}
}
// second couch
self.onInputChange = function() {
var now = getTime();
var newInputValue = self.input.value;
var inputValue = self.lastSearch;
if(/* text has changed */ inputValue!=newInputValue
&& /* enough letters to update */ (newInputValue.length==0 || newInputValue.length>=self.minTextLength) ) {
self.textChange(inputValue);
if(now-self.lastCall>self.minInterval) { /* min interval elapsed */
/// UPDATE
inputValue = newInputValue;
self.lastSearch = inputValue;
self.callback(inputValue, self.input);
self.lastCall = getTime();
self.timer = false;
}
else {
self.timer = setTimeout(self.onInputChange, self.minInterval-(now-self.lastCall)+10);
}
}
};
self.input.addEventListener('keyup', self.onKeyup, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment