2016-08-12 154 views
0

我想知道是否反复使用多个setTimeOut()会导致延迟问题。多setTimeOut导致延迟?

我的代码是在这里:

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

我,当我点击一个按钮,重新专注于#target每次调用它。但是第一对夫妇尝试(点击)工作得很好,而且之后“关注行动”开始放缓。大约30次点击,执行“焦点行动”至少需要3秒钟,并且不断增加延迟。

是由浏览器造成的吗?感谢您的任何建议。

回答

1

您能否分享您的代码重现该行为的例子?

基本上在某些情况下,它可能是最好的做法,取消以前的超时,当另一个超时过程中,或先前请求完成之前不会建立新的,

但是例如本拨弄你可以看到它可以毫无延迟地工作,所以它很难在没有更多代码的情况下理解问题的根源。

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" />

一个更好的做法可能是:

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" />

+0

不错!我的代码和你的第一个样本完全一样。感谢您的建议! –