Question

I have a probably really simple question but did not find anything about this or maybe did not find the right words for my problem.

If have a function to be executed on keypress which also changes my variable A - fine, and it works. But now I want to give an alternative value to my variable A if the keypress event is not happening.

So I'm looking for the correct command for the naive logic of

if ("keypress event happens") {
  A = 1
} else {
  A = 2
} 

Is there any way to do that in js or jquery with simple true/false checks for the key event? I've been trying and trying and it did not work once.

Was it helpful?

Solution

Usually, the way one solves this problem is with a setTimeout(). You set the timer for N seconds. If the keypress happens, you cancel the timer. If the keypress doesn't happen, the timer will fire giving you your alternate event.

You probably wrap this in some sort of function that you can trigger whenever you want, but you didn't share the overall context so this is just the general idea:

$("#myObj").keypress(function(e) {
    if (timer) {
        clearTimeout(timer);
    }
    // process key
});

var timer = setTimeout(function() {
    timer = null;
    // key didn't happen within the alltoted time so fire the alternate behavior
}, 5000);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top