On the de-dithering of js function

The

page is simple, just an input box

<input type="text" v-model="keyword" @keyup="search($event)">

js:

methods:{
    //
    search:function(e){
        var timer;
        if(e.keyCode != 32){ //
            clearTimeout(timer);
            timer = setTimeout(()=>{
                console.log("");
            }, 1000)
        }
    }
}

when I typed "123", I printed it three times

clipboard.png

what I want:
when I typed "123", I printed it once


var timer; is defined outside the search. If a new timer is not defined every time it is triggered, it will not be the handle of the last settime


because your timer is redeclared every time you click. Just put the timer declaration outside


search:function(e){
        var timer; // timer,clearTimeouttimeundefined
        if(e.keyCode != 32){ //
            clearTimeout(timer);
            timer = setTimeout(()=>{
                console.log("");
            }, 1000)
        }
    }
.
Menu