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

前端 未结 27 2627
半阙折子戏
半阙折子戏 2020-11-21 23:32

I’ve got a search field. Right now it searches for every keyup. So if someone types “Windows”, it will make a search with AJAX for every keyup: “W”, “Wi”, “Win”, “Wind”, “Wi

27条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 00:08

    If someone like to delay the same function, and without external variable he can use the next script:

    function MyFunction() {
    
        //Delaying the function execute
        if (this.timer) {
            window.clearTimeout(this.timer);
        }
        this.timer = window.setTimeout(function() {
    
            //Execute the function code here...
    
        }, 500);
    }
    

提交回复
热议问题