我的主要問題是:clearTimeout()是否停止計時器並且不在定時器內執行函數?或者它只是清除超時並立即執行該功能?javascript cleartimeout()問題
這是我的示例
$('input').keyup(function(){
var thisClass = $(this).attr('class').split(" ");
var thisValue = $(this).val();
var thisError = $(this).parent().siblings('.error');
var thisTimeout;
if(thisClass[1] == "letters"){
if(thisValue.length <= 1){
thisTimeout = setTimeout(function(){
thisError.html("You must have at least 2 characters");
thisError.show();
}, 800);
} else {
clearTimeout(thisTimeout);
thisError.hide();
thisError.html("");
}
}
});
這是一個代碼檢查的一部分,以查看是否輸入框在其具有至少2個字符。 當前,如果它有2個或更少的字符,此代碼在800毫秒後執行超時。當輸入框有兩個以上的字符時,如果我輸入的速度夠快,當我輸入完成後,錯誤框仍然顯示。我可以通過輸入更多字符來清除錯誤,但如果我要快速輸入自己的名字,那麼輸入完畢後會顯示錯誤。
我也有這樣的一段代碼:
$('input').keydown(function(){
clearTimeout(thisTimeout);
thisError.hide();
});
希望,如果我繼續打字 思考它會清除錯誤?
'thisTimeout'應被宣佈出來的'if',所以它的可見太 – 2013-03-15 18:12:22
我先試試這個,雖然我得到了相同的結果 - 我已經更新了上面的代碼以顯示以前的代碼 - 並且我會保持這種方式 – ntgCleaner 2013-03-15 18:14:05
@ntgCleaner Javascript引擎會將'thisTimeout'移出'if'函數外,這就是爲什麼它仍然有效。 – 2013-03-15 18:16:16