Last active
August 29, 2015 14:15
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
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