OnKeyUp JavaScript Time Delay?

无人久伴 提交于 2019-11-28 20:22:44
mck89

Try this:

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

In this way every time a key is pressed, the timeout will be deleted and the set again.

Another approach, without globals:

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

Usage:

Attaching the event through JavaScript:

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

Or using an inline event handler (not so much recommended) as you have in your example:

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

Try a demo here.

Really useful post!

Another approach without globals, using function properties:

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

setTimeOut() would be the one ;)

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

link text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!