Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript onkeyup delayed function call [duplicate]

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 milliseconds 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.

like image 970
ZeDonDino Avatar asked Apr 26 '26 12:04

ZeDonDino


1 Answers

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.