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?
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?
Share Improve this question asked Aug 9, 2012 at 1:15 NRGdallasNRGdallas 3952 gold badges8 silver badges20 bronze badges 4- have you tried the sleep() function? – MimiEAM Commented Aug 9, 2012 at 1:19
-
@MimiEAM what
sleep()
function would that be? – Pointy Commented Aug 9, 2012 at 1:20 - are you sure its hardware issue? – The Internet Commented Aug 9, 2012 at 1:21
- @Pointy the one from JQuery, bine with stoppropagation it should do the trick – MimiEAM Commented Aug 9, 2012 at 1:24
3 Answers
Reset to default 5is 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;
}
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"
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/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?