Javascript onkeyup delayed function call [duplicat

2019-05-26 06:36发布

问题:

This question already has an answer here:

  • How to delay the .keyup() handler until the user stops typing? 25 answers

I want to make a javascript function that fires onkeyup event and its task is to call a main resolver function but only if no keys are fired for at least x miliseconds where x is the functions parameter.

For instance:

we have html code

<body>
    <input type="text" id="suggestion" onkeyup="callMe(200);"/>
</body>

and javascript something like:

<script type="text/javascript">
    function callMe(ms)
    {
        //wait at least x ms then call main logic function
        // e.g. doMain();
        alert("I've been called after timeout"); //for testing purposes
    }
</script>

So while i'm typing the alert won't be called until you don't type anything for at least x ms.

回答1:

You can use a timer, you also need to clear the previous timer each time.

To achieve this, better use "wrapper" function:

<input type="text" id="suggestion" onkeyup="DelayedCallMe(200);"/>

And the JavaScript:

var _timer = 0;
function DelayedCallMe(num) {
    if (_timer)
        window.clearTimeout(_timer);
    _timer = window.setTimeout(function() {
        callMe(num);
    }, 500);
}

This will execute the function 500 milliseconds after the last key up event.

Live test case.



回答2:

<input type="text" id="suggestion" onkeyup="callMe(200);"/>
<script>
    var to;
    function callMe(ms) {
       clearTimeout(to);
       to = setTimeout(function(){
           alert("I've been called after timeout");
       }, ms);
    }
</script>

​

DEMO