Fabian Knauf
Fabian Knauf

Reputation: 125

only one keyup event for certain time

I check if someone's pressing space to start a css transition:

$(document).bind('keyup', function(e) {
    if (e.which == 32) {
        angle = 7200 + (Math.ceil( (Math.random() * 3600) / 45) * 45);
        $("#wheel").css("transform", "rotate(" + angle + "deg)")
    }
})

This transaction takes 10s.

I now want to prevent a new fired keyupevent before the 10s are done.

I tried with events ontransitionrun and ontransitionend, but these don't seem to be fired at all:

$("#wheel").bind('ontransitionend', function(e) {
    console.log('end');
})

And I also tried to delay my keyup function, but that does not work, too.

So how can I either check if my transition is still running or how can I prevent a new keyup event for 10 seconds?

Upvotes: 0

Views: 478

Answers (3)

Fabian Knauf
Fabian Knauf

Reputation: 125

Stupid me - I didn't see the wood for the trees!

$("#wheel").bind('ontransitionend', function(e) {

is of course wrong, as it has to be

$("#wheel").bind('transitionend', function(e) {

So this one works as expected:

var act = 0
$("#wheel").bind('transitionrun', function(e) {
  act = 1;
})
$("#wheel").bind('transitionend', function(e) {
  act = 0;
})
$(document).bind('keyup', function(e) {
  if (e.which == 32 && act == 0) {
    angle = angle + 7200 + (Math.ceil( (Math.random() * 3600) / 45) * 45);
    $("#wheel").css("transform", "rotate(" + angle + "deg)")
  }
})

Thanks for your suggestions, which both are working.

Upvotes: 0

user3054235
user3054235

Reputation: 11

You can use $.debounce In your exemple you could use something like that:

$(document).keyup( $.debounce( 10*1000, function(e) {
    if (e.which == 32) {
        angle = 7200 + (Math.ceil( (Math.random() * 3600) / 45) * 45);
        $("#wheel").css("transform", "rotate(" + angle + "deg)")
    }
}))

Upvotes: 1

Sébastien
Sébastien

Reputation: 12139

You can remove your event handler as soon as it is executed, than reattach it after 10 seconds:

var keyupHandler = function(e) {
    if (e.which == 32) {
        $(document).off('keyup');
        angle = 7200 + (Math.ceil( (Math.random() * 3600) / 45) * 45);
        $("#wheel").css("transform", "rotate(" + angle + "deg)");
        setTimeout($(document).on('keyup', keyupHandler), 10000);
    }
}
$(document).on('keyup', keyupHandler);

Upvotes: 1

Related Questions