Skip to content

Instantly share code, notes, and snippets.

@erobit
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erobit/1ea76df19bb07f32786c to your computer and use it in GitHub Desktop.
Save erobit/1ea76df19bb07f32786c to your computer and use it in GitHub Desktop.
Input field scanner - to detect when input is entered extremely fast (i.e. by a scanner and not a human) and execute a callback method
function Scanner(id, opts, cb) {
this.robot = false;
this.count=0;
this.tick = 0;
this.total = 0;
this.avg = 0;
this.timer = null;
this.callback = arguments.length == 3 ? cb : opts;
this.opts = arguments.length == 2 ? {} : opts;
this.scanThreshold = opts.scanThreshold || 10;
this.timeout = opts.timeout || 3000;
this.logger = opts.logger || false;
this.obj = document.getElementById(id);
}
Scanner.prototype.scan = function() {
clearTimeout(this.timer);
this.timer = setTimeout(this.complete.bind(this), this.timeout);
if(this.obj.value == ''){
this.reset();
return;
}
var d = new Date();
var newTick = d.getTime();
var diff = newTick - this.tick;
this.count++;
if(this.tick != 0) {
this.total += diff;
this.avg = this.total / this.count;
}
this.tick = newTick;
this.robot = this.avg > 0 && this.avg < this.scanThreshold;
this.log();
};
Scanner.prototype.log = function() {
if(this.logger) {
console.log('avg keystroke duration=' + this.avg + ', robot=' + this.robot);
}
};
Scanner.prototype.complete = function() {
if(this.callback != null && this.robot) {
this.callback(this.obj.value);
}
};
Scanner.prototype.reset = function() {
this.count=this.tick=this.total=this.avg=0;
};
@erobit
Copy link
Author

erobit commented Feb 13, 2015

// testing using jquery
$(document).ready(function(){
  var scanner = new Scanner('box', { timeout: 1000 }, function(result){ alert('scan complete='+result); });
  $('#box').on('keyup', function(e){ scanner.scan(); }); 

  //simulate a scanner
  var e = $.Event('keyup');
  var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");        
  alphabet.map(function(l,i){           
    e.keyCode = parseInt(97+i);
    $('#box').val($('#box').val()+l);
    $('#box').trigger(e);
  });
});

@erobit
Copy link
Author

erobit commented Feb 13, 2015

<html>
  <head>
    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="test.js"></script>
  </head>
<body>
  <input id="box" type="text"/>
</body>
</html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment