unknown
unknown

Reputation: 866

increment variable on set interval using javascript?

First of all this is the mini javascript script:

 f = 1
 $(".thumb").hover(function() {
       intervalId = setInterval($(this).text(f++), 400));
  });

Im trying to get the .thumb text to increase while the users moise is over it, It increases when i hover out and hover over again, but i want to increase while the user is hovered on top of the element.

Upvotes: 0

Views: 3353

Answers (4)

jfriend00
jfriend00

Reputation: 707436

You would have to pass an actual function to setInterval() like this:

 f = 1
 $(".thumb").hover(function() {
       var self = $(this);
       intervalId = setInterval(function() {self.text(f++)}, 400));
  });

What you are doing in your original code is passing the result of calling $(this).text(f++) which executes immediately to setInterval(). Since that doesn't return a function, there is no callback function for setInterval() so nothing runs on the interval.


If you also want to stop the interval when you stop hovering, then you could do this:

 var f = 1;
 var intervalId;
 $(".thumb").hover(function() {
     var self = $(this);
     if (intervalId) {
         clearInterval(intervalId);
     }
     intervalId = setInterval(function() {self.text(f++)}, 400));
 }, function() {
     f = 1;
     clearInterval(intervalId);
     intervalId = null;
 });

Upvotes: 1

MattDiamant
MattDiamant

Reputation: 8771

Here is a fiddle that does what you want: http://jsfiddle.net/2pdnP/

var f = 1;
var intervalId = null;
 $(".thumb").hover(function() {
    var self = this;
    intervalId = setInterval(function() {$(self).text(f++)}, 400);
 }, function () {
    clearInterval(intervalId);
 });

You need to have intervalId defined outside of your hoverIn scope, and then deactivate it when you hover out.

Upvotes: 1

darshanags
darshanags

Reputation: 2519

Try:

var f = 1,
    intervalId;

$(".thumb").hover(function () {
    $this = $(this);
    intervalId = setInterval(function () {
        $this.text(f++);
    }, 100);
}, function () {
    clearInterval(intervalId);
});

Fiddle here

Upvotes: 2

Adam Plocher
Adam Plocher

Reputation: 14233

This works, but there might be a simpler way:

<script>
 var f = 1
 var intervalId;
 var started = false;

 $(".thumb").hover(function() {
    started = true;
  },
  function () {
    started = false;
  });

  intervalId = setInterval(incrementDiv, 400);

  function incrementDiv() {
    if (started) {
        $(".thumb").text(f++);
    }
  }
</script>

This will start incrementing the value while the mouse is hovered over the element, and stop when the mouse cursor moves away.

Upvotes: 0

Related Questions