JQuery - detect if input is pressed more than X times in X seconds

I have an AJAX chat, and this is the code for sending 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 would like someone to press enter more than 3 times in 2 seconds, and on $('#usermsg')

What will be the shortest and best way to do this?

+5
source share
2 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({ // ............. }); } }); 
+4
source

 var countTime=0; $('#usermsg').on('keydown', function(e){ var key = e.which; if(key == 13) { // the enter key code if (countTime==0){ countTime++; setTimeout(function(){countTime=0},2000) var clientmsg = $("#usermsg").html(); if((jQuery.trim(clientmsg)).length==0) { return false; } $.ajax({ // ............. }); } else { countTime++; if (countTime>=3) countTime=0; } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="usermsg"/> 
0
source

Source: https://habr.com/ru/post/1260705/


All Articles