sharath
sharath

Reputation: 3626

Avoid race condition in javascript (while using settimeout)

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 ?

Upvotes: 4

Views: 3656

Answers (4)

Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10877

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

Upvotes: 2

Darshana Thennakoon
Darshana Thennakoon

Reputation: 36

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>

Upvotes: 0

ManavM
ManavM

Reputation: 3108

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.

Upvotes: 6

Warren Wan
Warren Wan

Reputation: 77

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

<button onClick='onClick()'/>

var onClick = () => {clearTimeout(yourTimer); yourFunc()}

Upvotes: -1

Related Questions