我要做的是当你持有 w 或 s 时,它应该每秒调用一次函数。但是现在它只会延迟第一次通话,然后每秒钟拨打12次电话。提前感谢任何会回答的人。我想要你的信息只是问。
<!DOCTYPE html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function call(direction) {
$.ajax({ url: '/' + direction });
}
</script>
<script>
document.onkeydown = function (event) {
var key_press = String.fromCharCode(event.keyCode);
var key_code = event.keyCode;
if (key_press == "W") {
direction = 'down';
} else if (key_press == "S") {
direction = 'up';
}
var update = setTimeout(function () {
call(direction)
}, 250);
}
document.onkeyup = function (event) {
clearTimeout(update);
}
</script>
答案 0 :(得分:0)
<script type="text/javascript">
function call(direction) {
$.ajax({ url: '/' + direction });
}
var update, direction, key = null;
document.onkeydown = function (event) {
var key_press = String.fromCharCode(event.keyCode);
var key_code = event.keyCode;
if (key_press == "W" && key != "W") {
key = "W";
direction = 'down';
update = setInterval(function () { call(direction); }, 1000);
} else if (key_press == "S" && key != "S") {
direction = 'up';
key = "S";
update = setInterval(function () { call(direction); }, 1000);
}
}
document.onkeyup = function (event) {
clearInterval(update);
}
</script>
答案 1 :(得分:0)
三这个
$(document).ready(function(){
$(document).on('keydown',function(e){
// content
});
});
答案 2 :(得分:0)
使用setInterval而不是setTimeout。还要考虑更新为全局变量。
var update = '';
document.onkeydown = function (event) {
var key_press = String.fromCharCode(event.keyCode);
var key_code = event.keyCode;
if (key_press == "W") {
direction = 'down';
} else if (key_press == "S") {
direction = 'up';
}
if (!update) {
update = setInterval(function () {
call(direction)
}, 1000);
}
}
document.onkeyup = function (event) {
clearInterval(update);
update = '';
}
答案 3 :(得分:0)
这与debounce函数的工作方式非常接近,这是我试图解决您的问题:
function debounce(callback, ms){
var timeOutId;
window.addEventListener('keydown', function(evt){
var key = String.fromCharCode(evt.keyCode);
if(['W','S'].indexOf(key) !== -1 && !timeOutId){
timeOutId = setTimeout(function(){
callback(evt);
timeOutId = null;
}, ms);
}
});
window.addEventListener('keyup', function(evt){
clearTimeout(timeOutId);
});
}
debounce(function(){ /* your function */}, 1000);
JSFiddle上的演示。