2009-09-04 254 views
23

嗨,再次大師的網絡:) 現在,我有一個新的愚蠢的問題,我要求原諒我。我到處閱讀這個解決方案,但沒有找到適用於我的解決方案。OnKeyUp JavaScript時間延遲?

我有:

<input name="domain" type="text" id="domain" onKeyUp="javascript:chk_me();"> 

所有我問的是如何讓一個按鈕按下後,這個不檢查,但後說1000毫秒鍵盤閒置?

回答

34

試試這個:每一個鍵被按下時

var timer; 
function chk_me(){ 
    clearTimeout(timer); 
    timer=setTimeout(function validate(){...},1000); 
} 

這樣,超時將被刪除和集合再次。

+2

我認爲'var定時器'需要在功能體外 – Rodrigo 2009-09-04 22:17:19

+0

你是正確的定時器必須設置功能外,我已經編輯答案 – mck89 2009-09-04 22:18:23

+0

謝謝!這個地段的最佳答案是公平的。 – Shog9 2009-09-04 22:22:30

-2

的setTimeout()將是一個;)

<input name="domain" type="text" id="domain" onKeyUp="setTimeout('chk_me()',1000);"> 

link text

+0

調用'chk_me時,這將不保留'this'上下文變量的值()'。此外,使用'setTimeout()'的變體來獲取並評估包含代碼的字符串在這種情況下是沒有意義的,在所有情況下都是混亂的。 – Shog9 2009-09-04 22:17:56

+0

嗨Berzemus,謝謝你的回覆。 我已經準備好了這個。它有效,但問題是它不會延遲腳本執行本身。它延遲每一個按鍵後... – Spoonk 2009-09-04 22:17:58

16

另一種方法,沒有全局:

var typewatch = function(){ 
    var timer = 0; 
    return function(callback, ms){ 
     clearTimeout (timer); 
     timer = setTimeout(callback, ms); 
    } 
}(); 

用法:

附加事件通過JavaScript:

window.onload = function() { 
    document.getElementById('domain').onkeyup = function() { 
     typewatch(function(){alert('Time elapsed!');}, 1000); 
    }; 
}; 

或使用內聯事件處理程序(與其說推薦),如你在你的例子:

<input type="text" name="domain" id="domain" 
    onKeyUp="typewatch(function(){alert('Time elapsed!');}, 1000);"/> 

試試演示here

+1

是什麼讓你覺得typewatch不是全球性的? – 2009-09-04 22:45:05

+1

是typewatch是全局的,但我的意思是說,** timer **變量不在全局範圍內,並且只能由typewatch函數訪問。 – CMS 2009-09-04 22:48:33

0

真的很有用的帖子!

沒有全局的另一種方法,使用功能性:

function chk_me(){ 
    if(typeof timer !== undefined){ 
    clearTimeout(this.timer); 
    } 
    this.timer=setTimeout(function validate(){validate(...)},1000); 
}