Avoid race condition in javascript (while using se

2019-08-13 01:55发布

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
4条回答
Melony?
2楼-- · 2019-08-13 02:14

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

查看更多
干净又极端
3楼-- · 2019-08-13 02:17

Clear your setTimeout callback when the button is pressed, for example:

<button onClick='onClick()'/>

var onClick = () => {clearTimeout(yourTimer); yourFunc()}
查看更多
霸刀☆藐视天下
4楼-- · 2019-08-13 02:34

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.

<!DOCTYPE html>
 <html>
  <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script>
     var myVar;
     $(document).ready(function(){
       myVar = setInterval(myFunctionInterval, 5000);
     });

     function myFunctionInterval() {
       alert("Hello (From Interval) !");
     }

     function clearLoop() {
       clearInterval(myVar);
       myVar = setInterval(myFunction, 5000);
     }

     function myFunction() {
       alert("Hello (From Button)!");
     }
    </script>
   </head>
   <body>

      <button onclick="clearLoop()">Click me</button>

   </body>
  </html>
查看更多
Luminary・发光体
5楼-- · 2019-08-13 02:37

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.

查看更多
登录 后发表回答