Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - detect if enter is pressed more than X times in X seconds

Tags:

I got an AJAX chat and this is the code to send messages:

$('#usermsg').keydown(function(e) {
    var key = e.which;
    if(key == 13)  // the enter key code
    {
        var clientmsg = $("#usermsg").html();
        if((jQuery.trim(clientmsg)).length==0)
        {
            return false;
        }

        $.ajax({
             // .............
        });
    }
});

I'd like to detect if someone pressed enter more than 3 times in 2 seconds while on $('#usermsg')

What would be the shortest and best way to do it?

like image 329
Eddy Unruh Avatar asked Dec 02 '16 12:12

Eddy Unruh


1 Answers

var enterCounter = 0;

$('#usermsg').keydown(function(e) {
    var key = e.which;
    if(key == 13) { // the enter key code        

        if (++enterCounter > 3) alert('pressed enter more than 3 times in 2 seconds');
        setTimeout(function(){enterCounter--;}, 2000);

        var clientmsg = $("#usermsg").html();
        if((jQuery.trim(clientmsg)).length==0) {            
            return false;
        }

        $.ajax({
             // .............
        });
    }
});
like image 159
ixpl0 Avatar answered Sep 25 '22 16:09

ixpl0