简体   繁体   English

仅在按下键一次时执行

[英]Only Execute if Key is pressed Once

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. 问题在于,每当我按m键时,setTimeout都会重新执行。 How can I keep it so that only if I press & hold once , the setTimeout executes. 我如何保持它,以便仅当我按住 一次时 ,setTimeout才会执行。 (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. 在您的setTimeout函数中,将此值更改为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. 在有条件地检查键码时,请检查并确保setTimeout函数仅在此布尔值设置为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. 如果需要一些持久性,请考虑使用sessionStorage。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM