Search code examples
javascripttimeoutdom-eventsbuttonclick

Button Click and Timeout calling the same function in javascript


I am working on an ionic project, and as part of this project, the user will have to complete a timed task. They have to answer a multiple choice question in 15~ seconds, otherwise they fail the task.

I currently have a timeout in the background, which will call function "evaluate" in the background, and disable the multiple choice answer buttons. This function is also called by the click of one of the multiple choice answer buttons.

Is there a danger of an edge case where the user selects the button just as the timeout calls the evaluate function, leading to the function being called twice? How can I avoid this?


Solution

  • As far as I known, there is no way to have a "race condition" in a web browser session, basically because each tab in a web browser runs in a single thread, so your logic will runs in a single runloop. You can use this fact to implement a flag indicating what happens first, but (honestly) this is pretty ugly.

    I think the most elegant solution should be to make the function evaluate idempotent, that way, you don't care if is called several times.