简体   繁体   中英

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?

You could have a variable named something like "eval_running" that you check in your evaluate function. If it is false, you set it to true and proceed evaluating. If it is true, you return from the function without evaluation. When you display the next task, you reset the variable to false.

That would prevent any kind of race condition. The time frame in which a double execution could occur depends on how long the eval function is working in the background. Chances are, you do not need to worry about this.

The best approach in this scenario is not very complicated. So the timeout trigger and also the submit button are calling the same evaluate function.

All you need to do is this. Disable the submit button immediately at the opening of the function and then write whatever you want to do. So if the timeout calls the function first, the button will be disabled before executing the operations, and the user cannot click the button anymore. If the button is clicked first, then it goes as it should and there's no complication here.

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.

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