OnKeyUp JavaScript Time Delay?

你说的曾经没有我的故事 提交于 2019-12-17 22:45:44

问题


Hi Again Masters Of The Web :) Now, I have got a new stupid question, and I am asking to forgive me. I read everywhere about this solution, but didn't find the one that works for me.

I have got:

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

All I am asking is how to make this not to check after a button is pressed, but after to say 1000 miliseconds of keyboard inactivity?


回答1:


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.




回答2:


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.




回答3:


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);
}



回答4:


setTimeOut() would be the one ;)

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

link text



来源:https://stackoverflow.com/questions/1381751/onkeyup-javascript-time-delay

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