简体   繁体   English

JavaScript - 在指定的时间段内侦听多个事件

[英]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? 有没有办法在一段时间内使用JavaScript监听HTML元素上的多个事件?

For example, I want to see if the user clicks an element 5 times within 2500 milliseconds or something like that. 例如,我想看看用户是否在2500毫秒内点击一个元素5次或类似的东西。

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. 我想只是一个HTML元素上的点击事件,它会更新每次点击的点击次数,然后如果在指定的时间段内未达到指定的点击次数,则会重置计时器。 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. 我更喜欢它是纯JavaScript,但我可以使用jQuery作为最后的手段。

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(). 我也不想使用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. 此方法不需要任何Jquery或使用任何计时器,这作为额外的奖励,使其更准确。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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