javascript - 如果一个键被按下 500 毫秒触发一个函数
问题描述
在 JQuery 中,我知道有一个名为 的函数keydown
,但这确实允许我在每次调用回调时设置超时。
$(document).keydown(() => {
//do stuff
});
//do stuff
每次通话都太快了。我想在用户持有密钥时每 500 毫秒调用一次。有没有办法做到这一点?
解决方案
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()
});
推荐阅读
- c++ - 如果不是多个则使用 if 语句
- swift - 如何在 swift 中使用包含在 dict 中
- asp.net-core - 使用中间件更改 Request.Path 时,Razor 页面显示空白页面
- javascript - 如何遍历嵌套的 JSON (firebase)?
- java - 不断得到 java.io.NotSerializableException
- graphql - Apollo Link State 中的默认值的目的是什么?
- r - min 和 max 在 r 中产生错误的结果
- mysql - 在 jpa 中运行 sql 脚本时出现 sql 语法错误
- python - UnboundLocalError,我在 Intro 课程中,所以我需要将其简化为如何解决此错误
- android - 带有活动的 BottomAppBar 动画