简体   繁体   中英

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).

i write this function but it gets on display only 11111111 in loop here is my code:

 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.

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. 100ms, if yes then call a function that continues the main program. The Waiting thread may then also check and count keypresses, eg. in global variables as a basic solution.

use "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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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