MaikThoma
MaikThoma

Reputation: 41

jQuery number not detected

I got this little piece of code that checks every 3 seconds if #button is hovered. If it is, it resets. If it's not hovered it should log a line that says 'Too late!' but it doesn't. I think it has something to do with the if-statement where it checks for the number.

var seconds = 3;
var timer;

$('#button').hover(function(){
  seconds = 3;
});

timer = setInterval(function(){
  --seconds;
  console.log(seconds);
}, 1000);

if (seconds == 0){
  console.log('Too late!');
} else {
  // do nothing
}

Upvotes: 0

Views: 46

Answers (2)

PaulBinder
PaulBinder

Reputation: 2052

Your "too late" function is running outside of your timer. Thus it will only run once and never again.

var seconds = 3;

setInterval(function(){
  --seconds;
    if (seconds == 0){
  alert('Too late!');
} 
  console.log(seconds);
}, 1000);

try something like that

Upvotes: 0

Farax
Farax

Reputation: 1477

Your code is outside your interval function. So while your interval function gets called after every second, the code outside gets called only once and never again. You should try something like this

var seconds = 3;
var timer;

$('#button').hover(function(){
  seconds = 3;
});

timer = setInterval(function(){
  --seconds;

 if (seconds == 0){
     alert('Too late!');
} else {
  // do nothing
}
}, 1000);

Here is the code in action Fiddle

Upvotes: 1

Related Questions