I have a JS function which gets called when a button is clicked. The same function gets called after a timeout too (using setTimeout). How can I avoid a race condition when somebody clicks the button and setTimout gets called at the same time ?
标签:
javascript
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
The JS function that gets called when a button is clicked is a callback function. The JS function that gets executed after a timeout is also a callback function. In your case, these 2 just happen to be the same. Both of them will be placed on the task queue from which the JS event loop will move them to the call stack when the call stack is clear. When each one of them is placed in the call stack, they gets executed. So after the first one is placed on the queue, it gets executed. Then the call stack is clear. Then the JS event loop pulls the second from the task queue and place on the call stack.
The JS runtime can only do one thing at a time. So there's no race condition.
This video https://www.youtube.com/watch?v=8aGhZQkoFbQ can describe in more details
Clear your setTimeout callback when the button is pressed, for example:
You can use 'setInterval' instead of 'setTimeout'. So in the button click you can clear the interval and set the interval again. You can refer the code below.
You seem to be thinking that these two functions might be called at exactly the same time so it will cause a race condition. But Javascript uses a single threaded Event Loop which means these functions will pushed to a stack of functions that would be executed one by one no matter when they are called.