3

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ZeDonDino
  • 5,072
  • 8
  • 27
  • 28
  • 1
    You can't "wait" in Javascript, but you could use a global variable to store a timeout (created with `setTimeout`). When each `keyup` event occurs, clear (if present) the existing timeout and set the next one. What have you already tried? Where's your code?. – David-SkyMesh Dec 17 '12 at 08:47

2 Answers2

9

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.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
1
<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

Okan Kocyigit
  • 13,203
  • 18
  • 70
  • 129