我想在 500 毫秒后执行一个 javascript 函数,但不是在按下某个键时执行,如下所示:
jQuery(function($) {
$('.class').keyup(function(Key) {
setTimeout(function(){
// excecute this not when any key is pressed
},500)
})
})
最佳答案
您需要将超时标识符存储在某处,如果在下一个 keyup 事件期间还没有超过 500 毫秒,则将其清除。将这个id保存在相关input的data属性中比较方便:
$('.class').keyup(function (Key) {
clearTimeout($(this).data('timeout'));
$(this).data('timeout', setTimeout(function () {
alert('pressed');
}, 500));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="class" placeholder="Type something">
关于Javascript 在 500 毫秒后执行函数,但在按键时返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29684919/