Christian Zschunke
Christian Zschunke

Reputation: 21

Start setInterval on mouseenter // reset on mousleave // stopping setInterval after 1 second

I'm rather new to javascript and hit a wall with the follwing problem. I am trying to decrease a variable from 1000 to 0 while hovering over an element. The variable should also reset to 1000 if the mouse leaves the element.

After some research I got most of it working, but I can't figure out how to get setIntervall to stop counting after the variable reached 0. This is what I came with after looking around on stackoverflow.

var f = 1000, intervalId;
if (f > 0) 
{
    $(".thumb").hover(function () 
    {
        $this = $(this);
        intervalId = setInterval(function () 
        {
            $this.text(f--);
        }, 1);
    }, function () 
    {
        clearInterval(intervalId);
        f = 1000;
    });
} 
else 
{
    clearInterval(intervalId);
}

I'm pretty sure it's a stupid mistake I am making here since I am new to programing, but if someone could point me into the right direction I would really appreciate your help.

FIDDLE around with the code

Upvotes: 0

Views: 301

Answers (2)

Danil Speransky
Danil Speransky

Reputation: 30453

Demo: http://jsfiddle.net/DVPcA/

var f = 1000;
var interval;

$(".thumb").hover(function () {
  $this = $(this);

  interval = setInterval(function () {
    if (f > 0) {
      $this.text(f--);
    } else {
      clearInterval(interval);
    }
  }, 1);
}, function () {
  clearInterval(interval);
  f = 1000;
});

Upvotes: 2

ripu1581
ripu1581

Reputation: 300

Updated the fiddle

http://jsfiddle.net/n74VW/56/

replace this line

$this.text(f--);

with

$this.text(f>0?f--:f=0);

Upvotes: -1

Related Questions