简体   繁体   English

如何等待2秒以Java语言输入

[英]How to wait 2 seconds for input in Javascript

I im programming tv remote control using javascript and need when user press number 1 function waits 2 seconds if user press one more time 1 (1 channel or 11 channel or 111channel). 我正在使用javascript编程电视遥控器,如果用户再按一次1(1通道或11通道或111通道),则需要按2号功能等待2秒。

i write this function but it gets on display only 11111111 in loop here is my code: 我写了这个函数,但它在循环中仅显示11111111 ,这是我的代码:

 function chChannel(pressed) {
     setInterval(function () {
         if (lengthCS < 3) {
             inputChannel += pressed;
             lengthCS = inputChannel.length;
         }
     }, 2000);

     // call function to change channel using variable value inputChannel for ex. 011
 };

Any solution please? 有什么解决办法吗?

So function need to wait 2seconds and then after 2seconds it gets value of pressed numbers in variable InputChannel so that i can then call function to change channel to number from Value InputChannel. 因此,函数需要等待2秒钟,然后等待2秒钟,它会在变量InputChannel中获取按下数字的值,这样我就可以调用函数以将Channel从Value InputChannel更改为数字。

Listening to keypresses and counting them is one well documented thing, but, in context with the actual topic, I would say, there is no correct Waiting method, other than to end the script with a timeout call being set to a function that repeatedly checks, whether the Time to wait has passed by, if not then selftrigger with setTimeout in eg. 听按键并计数是一本有据可查的东西,但是,在实际主题的背景下,我想说,没有正确的Waiting方法,除了将超时调用设置为可重复检查的函数来结束脚本外,等待时间是否已经过去,如果没有过去,则使用例如setTimeout进行自触发。 100ms, if yes then call a function that continues the main program. 100ms,如果是,则调用继续主程序的函数。 The Waiting thread may then also check and count keypresses, eg. 然后,等待线程还可以检查和计数按键,例如。 in global variables as a basic solution. 在全局变量中作为基本解决方案。

use "setTimeout". 使用“ setTimeout”。

var Timer;

function chChannel(pressed) {
    clearTimeout(Timer);
    Timer = setTimeout(function () {
        if (lengthCS < 3) {
            inputChannel += pressed;
            lengthCS = inputChannel.length;
        }
    }, 2000);

    // call function to change channel using variable value inputChannel for ex. 011
};

Have you considered using something like underscore's debounce function, would make things a lot simpler all round. 您是否考虑过使用下划线的反跳功能之类的东西,会使事情变得更加简单。

http://underscorejs.org/#debounce http://underscorejs.org/#debounce

May be something like this might work, on phone can't test it myself... 可能是这样的事情可能在电话上无法自己测试...

var inputChannel;

 function chChannel(pressed) {
     if (inputChannel <= 3) {
         inputChannel += pressed;
     } 
     else {
        inputChannel = pressed;
    }
    _.debounce(someFunction, 2000);
 };

As long as debounce keeps getting called within the delay it will not execute, and only execute once after the delay. 只要在延迟时间内不断调用防抖功能,它就不会执行,只会在延迟后执行一次。

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

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