首页 > 解决方案 > 如果一个键被按下 500 毫秒触发一个函数

问题描述

在 JQuery 中,我知道有一个名为 的函数keydown,但这确实允许我在每次调用回调时设置超时。

$(document).keydown(() => {
  //do stuff
});

//do stuff每次通话都太快了。我想在用户持有密钥时每 500 毫秒调用一次。有没有办法做到这一点?

标签: javascriptjquery

解决方案


I'm not sure if this is best approach, but this would be solve your problem

var pressedAt = 0
var timeStep = 500 // 500 ms

function checkKey(e) {
 if(pressedAt == 0) {
  pressedAt = Date.now() 
 }
 if (Date.now() - pressedAt >= timeStep) {
  console.log("Key Pressed");
  pressedAt = 0
 }
}

document.addEventListener("keydown", checkKey);
document.addEventListener("keyup", function(){
  pressedAt = 0
  console.clear()
});


推荐阅读