0

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?

4
  • have you tried the sleep() function? Commented Aug 9, 2012 at 1:19
  • @MimiEAM what sleep() function would that be? Commented Aug 9, 2012 at 1:20
  • are you sure its hardware issue? Commented Aug 9, 2012 at 1:21
  • @Pointy the one from JQuery, combine with stoppropagation it should do the trick Commented Aug 9, 2012 at 1:24

3 Answers 3

5

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; 
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.