简体   繁体   English

javascript中如何同时监听一个事件和一个定时器

[英]How to listen to an event and a timer at the same time in javascript

When the page is loaded, a timer with a random limit starts.加载页面时,将启动一个具有随机限制的计时器。 I want to trigger some actions when the timer has run out and the user has pressed a button.我想在计时器用完并且用户按下按钮时触发一些操作。

Update: Only when both two conditions are satisfied will the action start.更新:只有当两个条件都满足时才会开始动作。

Update 2: To be clear, if 'button clicked' is event A, 'timer goes out' is event B, then the condition is A and B, not A or B, that's a little bit counter-intuitive.更新 2:要清楚,如果“单击按钮”是事件 A,“计时器停止”是事件 B,那么条件是 AB,而不是 AB,这有点违反直觉。 (ps: release the click won't cancel event A) (ps:释放点击不会取消事件A)

const timeupEvent = new Event("timeup");

function f() {
    document.dispatchEvent(timeupEvent);
}

setTimeout(f, limit);

button.addEventListener("click", (event) => {
    document.addEventListener('timeup', action);
})

My code is shown as above.我的代码如上所示。 When the user clicks before the timer goes out, it runs smoothly, but when he clicks after that, the code can't run correctly.当用户在计时器熄灭之前点击时,它运行顺利,但是当他在之后点击时,代码无法正确运行。

I Believe that's because document.addEventListener('timeup', action) won't be triggered if the event is emitted before the execution of the code, but I don't have proper solutions for it.我相信这是因为如果事件在代码执行之前发出,则document.addEventListener('timeup', action)不会被触发,但我没有合适的解决方案。

Thanks for your help and advice!感谢您的帮助和建议!

Unless you actually need the timeup event you could simple check how much time has elapsed:除非你真的需要 timeup 事件,否则你可以简单地检查已经过了多少时间:

const pageLoadAt = Date.now();
const limit = 5000; // ms

button.addEventListener("click", (event) => {
    if (Date.now() - pageLoadAt >= limit) {
        action();
    }
});

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

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