I have a Javascript code that executes a function every time a button is pressed, however, my hardware setup is occasionally sending double inputs (ie pressing the button twice) - when this happens, they are a sheer milliseconds apart. is it possible to restrict the javascript from executing the function twice within say 50ms of time?
3 Answers
is it possible to restrict the javascript from executing the function twice within say 50ms of time?
Yes, you have to keep track of the last time you ran the function. Something like:
var lastTime = 0;
function buttonPressed() {
var now = new Date().getTime();
if(now-lastTime > 50) {
// do stuff
}
lastTime = now;
}
Comments
For a more universal solution, here is a wrapper to make prevent 'bounces' for any function:
var preventBounce = function(fn, ms) {
var _fn = fn;
var _firedAt = false;
var _ms = ms;
return function() {
var now = new Date().getTime();
if(!_firedAt || (_firedAt + _ms) <= now) {
_firedAt = now;
return _fn.apply(this, arguments);
}
}
}
This allows you to create a new function that prevents the function from firing if called within ms milliseconds of the last call.
For example:
test = preventBounce(alert, 5000);
test('example'); // alerts "example"
test('example'); // no action
// ...wait 5 seconds
test('example'); // alerts "example"
Comments
Yes you can. Set a flag on your first click (or key press). Set a timer to clear it. Proceed with your key press or click action only if the flag is not set.
var within50ms = false;
function clicked()
{
if(within50ms)
{
//the faulty click
}
else
{
//Go ahead
}
within50ms = true;
var timer = setTimeout(function()
{
within50ms=false;
}, 50);
}
Complete Example (with a 500ms delay for a realistic demo): http://jsfiddle.net/nivas/FFLGw/
That said, this is a hardware problem on your machine or is it expected on every machine that this app/page will be used from?
sleep()function would that be?