Home > Software engineering >  How to listen to an event and a timer at the same time in javascript
How to listen to an event and a timer at the same time in javascript

Time:12-06

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. (ps: release the click won't cancel event 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.

Thanks for your help and advice!

CodePudding user response:

Unless you actually need the timeup event you could simple check how much time has elapsed:

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

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

CodePudding user response:

To make sure that the timeup event is handled correctly in your code, you can add a flag that indicates whether the timer has run out or not. When the user clicks the button, check the flag and only execute the action if the timer has run out.

Here is an example of how you could do that:

const timeupEvent = new Event("timeup");
let timerHasRunOut = false;

function f() {
    // Set the flag to true to indicate that the timer has run out
    timerHasRunOut = true;
    document.dispatchEvent(timeupEvent);
}

// Start the timer
setTimeout(f, limit);

// Add an event listener for the "click" event on the button
button.addEventListener("click", (event) => {
    // Check if the timer has run out
    if (timerHasRunOut) {
        // If the timer has run out, execute the action
        action();
    }
});

CodePudding user response:

A solution might be to check if the timeup event was emitted before adding the event listener, like this:

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

Then assign true to timeupEvent.hasBeenEmitted when the timeup event is emitted.

  • Related