mheavers
mheavers

Reputation: 30158

javascript / jquery - avoid repeating evaluation of a conditional

I currently have a conditional running in jquery's scroll event, which doesn't seem to make a lot of sense since it will only execute once. I was wondering if there is any way to ensure that the conditional will only be evaluated once.

here's my code:

$window.scroll(function() {
  if (s1_doAnimate == true){
    s1_doAnimate = false;
  }
})

Upvotes: 0

Views: 135

Answers (2)

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

Use $.one

$(window).one('scroll', function(){
...
});

Upvotes: 3

Matt
Matt

Reputation: 75317

You can unbind the handler once the condition has been met;

$window.scroll(function foo /* give the function a name */ () {
  if (s1_doAnimate == true){
    s1_doAnimate = false;

    // Unbind the handler referenced by the name...
    $window.off(foo);
  }
})

Upvotes: 2

Related Questions