Multiple setTimeOut lead to latency?

I was wondering if using multiple setTimeOut() repeatedly will lead to latency problem.

My code is here:

setTimeout( function(){ $("#target").focus(); }, 50 );

I call this every time when I click on a button to re-focus on the #target. But the first couple attempts(clicks) work fine and fast, after that, the “focus action” start to slow down. Around 30 clicks, it takes at least 3 seconds for the execution of the “focus action” and keep increasing the latency.

Is that caused by the browser? Thanks for any suggestions.

Answer

Could you please share an example of your code that reproduce that behaviour?

Basically on some cases it could be best practice, to cancel previous timeouts when another timeout is in progress, or not creating new ones before the previous request have finished,

But for example with this fiddle you can see that it works perfectly fine without any delays, so its hard to understand the source of your problem without more code.

function clickFocus(){
   setTimeout( function(){ $("#target").focus(); }, 50 );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" onclick="clickFocus()">
focus
</button>
<input type="text" id="target" />

a better practice could be:

var awaitingFocus;
function clickFocus(){
  if(!awaitingFocus){
    awaitingFocus = setTimeout( function(){ 
      $("#target").focus();
      awaitingFocus = false;
    }, 50 );
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" onclick="clickFocus()">
focus
</button>
<input type="text" id="target" />