How to disable repetitive keydown in JavaScript [duplicate]

夙愿已清 提交于 2019-12-10 03:22:44

问题


I have a same problem like this guy How to disable repetitive keydown in jQuery , it's just that I'm not using jQuery so I'm having hard time translating it to "pure" JavaScript, anyways I have set switch-case of some keys and when I press and hold right arrow key my div is flying. Also if it's not a problem can you tell me what would be the easiest way to stop div movement when I let the right arrow key go, do I have to make a new switch case with clearInterval or?

switch (keyPressed) {
    case 39:
        setInterval(movFwr, 50);
        break;
}

function movFwr() {
    if (currPos == 1000) {
        a.style.left = 1000 + "px";
    } else currPos += 10;
    a.style.left = trenutnaPozicija + "px";
}

I'm sorry guys, I've been busy a bit, I'm testing all possibilities and so far I have seen some interesting suggestions. I'll test em all these days and then rate of what ever is that you do on this site. Great community I must say. Thank you all for your help :)


回答1:


Something like this should do the trick;

var down = false;
document.addEventListener('keydown', function () {
    if(down) return;
    down = true;

    // your magic code here
}, false);

document.addEventListener('keyup', function () {
    down = false;
}, false);



回答2:


To ignore key events caused by key repeats, keep track of which keys are pressed during the keydown and keyup events.

var pressedKeys = [];
function keydownHandler(e) {
    var isRepeating = !!pressedKeys[e.keyCode];
    pressedKeys[e.keyCode] = true;
    switch (e.keyCode) {
        case !isRepeating && 39:
            // do something when the right arrow key is pressed, but not repeating
            break;
    }
}
function keyupHandler(e) {
    pressedkeys[e.keyCode] = false;
}

To stop your div moving, you could keep track of the interval ids in an array, and clear the interval during the keyup event with something like clearInterval(intervalIds[e.keyCode]), but I'd probably switch to using setTimeout() and checking whether they key is down instead. That way, you don't have to keep track of another variable.

var pressedKeys = [];
function keydownHandler(e) {
    var isRepeating = !!pressedKeys[e.keyCode];
    pressedKeys[e.keyCode] = true;
    switch (e.keyCode) {
        case !isRepeating && 39:
            movFwr();
            break;
    }
}
function keyupHandler(e) {
    pressedkeys[e.keyCode] = false;
}
function movFwr() {
    if (pressedKeys[39] && currPos < 1000) {
        currPos += 10;
        a.style.left = currPos + "px";
        setTimeout(movFwr, 50);
    }
}

This way, you also automatically stop repeating the function as soon as the div reaches the right edge, instead of waiting for the user to release the arrow key.




回答3:


Track the last key pressed, if its the same as current ignore it by returning, and use clearInterval to stop the intervals

//global variables
var lastKey = 0;
var moveTimer = [];

//in keydown function
if(lastKey == keyPressed)
    return;
switch (keyPressed) {
    case 39:
        lastKey = keyPressed
        moveTimer[keyPressed] = setInterval(movFwr, 50);
        break;
}


//in a onkey up function
lastKey = null;
if(typeof(moveTimer[keyPressed]) != "undefined")
    clearInterval(moveTimer[keyPressed]);



回答4:


I would record the time and prevent action unless enough time has passed, for example using Date.now

var lastPress = 0;

function myListener() {
    var now = Date.now();
    if (now - lastPress < 1000) return; // less than a second ago, stop
    lastPress = now;
    // continue..
}

This can be made into a more generic function

function restrict(func, minDuration) {
    var lastPress = 0;
    return function () {
        var now = Date.now();
        if (now - lastPress < minDuration) return; // or `throw`
        lastPress = now;
        return func.apply(this, arguments);
    };
}
// now, for example
foo = function () {console.log('foo');};
bar = restrict(foo, 200); // only permit up to once every 200ms
bar(); // logs "foo"
bar(); // void as less than 200ms passed


来源:https://stackoverflow.com/questions/17514798/how-to-disable-repetitive-keydown-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!