Javascript在500毫秒后执行功能,但在按键时返回

Mar*_*ark 1 javascript jquery return settimeout

我希望在500ms之后执行一个javascript函数,但是在按下某个键时不会,例如:

jQuery(function($) {
    $('.class').keyup(function(Key) {
         setTimeout(function(){
              // excecute this not when any key is pressed
         },500)
    })
})
Run Code Online (Sandbox Code Playgroud)

dfs*_*fsq 5

如果在下一个keyup事件期间尚未传递500ms,则需要在某处存储超时标识符并清除它.将此id保存在相关输入的data属性中很方便:

$('.class').keyup(function (Key) {
    clearTimeout($(this).data('timeout'));
    $(this).data('timeout', setTimeout(function () {
        alert('pressed');
    }, 500));
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="class" placeholder="Type something">
Run Code Online (Sandbox Code Playgroud)