简体   繁体   中英

Last key pressed event?

How to know if a user stop typing?

Something like this:

$('#input').onkeyup(function(){
   //do something
});

But how you can know if that was the last .onkeyup event?

I think that needs a timer, to know when the user stop typing can be 2 seconds after the last .onkeyup... Some thing like that.

Ideas?

Yes, you are right... you can use a timer based solution like

jQuery(function ($) {
    //to store the reference to the timer
    var timer;
    $('#myinput').keyup(function () {
        //clear the previous timer
        clearTimeout(timer);
        //create a new timer with a delay of 2 seconds, if the keyup is fired before the 2 secs then the timer will be cleared
        timer = setTimeout(function () {
            //this will be executed if there is a gap of 2 seconds between 2 keyup events
            console.log('last')
        }, 2000);
    });
})

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM