I have the following code:

onkeyup = function(e) {
                if (e.keyCode == 77) { // the 'm' key
           setTimeout(function () {
            ... // my set timeout stuff
            }

The problem is that every time I press the m key, my setTimeout re executes. How can I keep it so that only if I press & hold once, the setTimeout executes. (any more times and nothing should executed).

Thanks, should be simple enough I hope.

有帮助吗?

解决方案

Store a Boolean variable like so:

var hasKeyBeenPressed = new Boolean(0);

In your setTimeout function, change this value to true. On your conditional checking for the keycode, check and ensure the setTimeout function only executes when this boolean value has been set to false.

var hasKeyBeenPressed = new Boolean(0);

onkeyup = function(e) {
    if (e.keyCode == 77 && hasKeyBeenPressed == 0) { // the 'm' key
        setTimeout(function () {
            hasKeyBeenPressed = 1;
            ... // my set timeout stuff
        }
    }
}

Under these conditions, your function will execute only one time.

If you need some persistence, consider using sessionStorage.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top