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

前端 未结 27 2575
半阙折子戏
半阙折子戏 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:02

    Use

    mytimeout = setTimeout( expression, timeout );
    

    where expression is the script to run and timeout is the time to wait in milliseconds before it runs - this does NOT hault the script, but simply delays execution of that part until the timeout is done.

    clearTimeout(mytimeout);
    

    will reset/clear the timeout so it does not run the script in expression (like a cancel) as long as it has not yet been executed.

提交回复
热议问题