javascript

Javascript - call a function when you finish typing


Let's say I have an input in which the user is going to type some text. When they finish typing I want to call a function automatically.

This is what I have done till now:

<input type="text" oninput="change();"/>

<script>
function changing(){
    alert('You stoped typing!');
}
function change(){
    clearTimeout(changing);
    setTimeout(changing, 2000);
}
</script>

What I am expecting:

When you type, change is called. It cancels the last changing that was supposed to run in 2 seconds and run a new changing within 2 seconds.

What actually happens:

When you type, change is called. It doesn't cancel the last changing that was supposed to run in 2 seconds but still run a new changing within 2 seconds. As you type, the first alert window will appear 2 seconds after you start typing and keep showing again and again one after another.

Is there something wrong in my code?


Solution

  • setTimeout() returns a timer ID. It is that timer ID that you must pass to clearTimeout() for it to work properly (you are passing the callback function to clearTimeout() and that is not how it works).

    So, you need to store the return value from setTimeout() into a variable in a lasting scope that you can then later pass to clearTimeout() like this:

    <input type="text" oninput="change();"/>
    
    <script>
    function changing(){
        alert('You stoped typing!');
    }
    var timer;
    function change(){
        clearTimeout(timer);
        timer = setTimeout(changing, 2000);
    }
    </script>