I need to know does a Javascript event will take precedence over normal code execution. I mean would that interrupt the code execution?. I want user to select some value from a dropdownlist and after the selection some processing is performed on it and then it is posted to the server. But if user does not select a value after a particular amount of time is elapsed, I select some value programmatically from the dropdown(based on predefined rules) and after processing post it to the server. Now I'm worried if I programmatically select some value from the dropdown and while that value is being processed user might also select some value from the user interface and data is posted twice to the server. Although Javascript is single threaded but I have read that some events interrupt the normal code execution. If that's true how can I resolve that issue.
-
The short answer is no. But your code should be structured accordingly and provide some logic to not double post. Set a flag on post, and wrap your submission in conditional logic to prevent the double post.Justin Herter– Justin Herter2017-07-24 20:14:43 +00:00Commented Jul 24, 2017 at 20:14
-
I would imagine the event would fire after the processing if your processing is long and blocks the thread(in which case a web worker would be a good idea). If it does block the select my not respond u till the processing is complete. Why not disable the select whilst executing your processing?ste2425– ste24252017-07-24 20:16:00 +00:00Commented Jul 24, 2017 at 20:16
-
Well if the code asynchronous? Sounds like to me you really need to write code that prevents duplicate submissions.epascarello– epascarello2017-07-24 20:17:02 +00:00Commented Jul 24, 2017 at 20:17
2 Answers
Browser events do not interrupt the execution of JavaScript code. JavaScript is effectively single-threaded and has a first-in first-out (FIFO) message queue for executing code. Regarding pre-emption:
Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates).
Similarly, setTimeout and setInterval also cannot interrupt code execution:
Calling setTimeout will add a message to the queue after the time passed as a second argument. If there is no other message in the queue, the message is processed right away; however, if there are messages, the setTimeout message will have to wait for other messages to be processed. For that reason the second argument indicates a minimum time and not a guaranteed time.