简体   繁体   中英

JavaScript - Listen for multiple events in a specified period of time

Is there is a way to listen for multiple events on an HTML element in a certain period of time using JavaScript?

For example, I want to see if the user clicks an element 5 times within 2500 milliseconds or something like that.

I am unable to go into a lot of detail currently. If need be I can put more detail in once I have more time.

I am thinking just a click event on an HTML element that updates the number of clicks each click and then resets a timer if the specified number of clicks has not been reached within a specified time period. I have tried some ways of accomplishing this and they have all failed.

I would prefer it be pure JavaScript, however I could use jQuery as a last resort.

If there is a completely obvious answer to this question I apologize ahead of time.

This is different from Click frequency calculation because I don't care about frequency too much. I care that a user clicked a few times in a certain period and only then run some code. I also would prefer to not use setInterval(). The two questions are certainly related, but I wouldn't say they are duplicates.

This method doesn't require any Jquery or make use of any timers, which as an added bonus, makes it much more accurate.

 var clicks = 0, firstClickTime = 0, clicksNeeded = 3, timeSpan = 1000; //time in milliseconds var myEvent = function(){ document.getElementById("myLabel").innerHTML="TRIGGERED!"; } document.getElementById("myButton").onclick = function(){ var dt = Date.now()-firstClickTime; if ( dt > timeSpan){ firstClickTime=Date.now(); clicks = 0; } if (++clicks >= clicksNeeded){ firstClickTime=0; clicks=0; myEvent(); } }; 
 <button id="myButton">Test</button> <button id="reset" onclick="document.getElementById('myLabel').innerHTML='Not Triggered';clicks=0;firstClickTime=0;">Reset</button> <h1 id="myLabel">Not Triggered</h1> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM