Kevin Garduño
Kevin Garduño

Reputation: 23

setTimeout keeps running after clearTimeout has been called

I am animating an object to move to 1 direction while the mouse is down and when the mouse clic goes up, the animation should stop.

I'm using setTimeout but it keeps moving for some time after I released the clic.

var stopmov
function tomove(){
    $('.plwid').animate({
        left: '+=1'
    },1);
    stopmov=setTimeout(function(){ tomove(); }, 1);
}

$('.plwid').mouseup(function(){
    clearTimeout(stopmov);
}).mousedown(function(){
    tomove();
});

http://jsfiddle.net/oa9bsqy1/

Upvotes: 0

Views: 1488

Answers (4)

AWolf
AWolf

Reputation: 8970

I've played around with setTimeout and setInterval but I think it's better to use a recursive call in the done callback of jQuery animate.

Also stopping is then pretty easy with $('.plwid').stop();.

Please find the demo below and here at JSFiddle.

function tomove() {
    $('.plwid').animate({
        left: '+=10'
    },
    100, 'linear', tomove);
}

$(document).mouseup(function () {
    $('.plwid').stop();
});

$('.plwid').mousedown(function () {
    tomove();
});
.plwid {
    position:relative;
    left:10px;
    background:red;
    width:100px;
    height:100px;
    cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="plwid"></div>

Upvotes: 0

user2124444
user2124444

Reputation: 21

Looks like every time tomove runs, it runs settimeout again, and the stopmov variable will only have the very most recent ...

So, just take

stopmov=setTimeout(function(){ tomove(); }, 1);

out of the first function. Call the settimeout when you're mousing down.

var stopmov
function tomove(){
    $('.plwid').animate({
        left: '+=1'
},1);
}
$('.plwid').mouseup(function(){
    clearTimeout(stopmov);
}).mousedown(function(){
    stopmov=setTimeout(function(){ tomove(); }, 1);
});

Upvotes: 0

TRGWII
TRGWII

Reputation: 648

var mouseIsDown = false;

function tomove(){
  $('.plwid').animate({
    left: '+=1'
  },1);
  if(mouseIsDown) setTimeout(function(){ tomove(); }, 1);
}

$('.plwid').mousedown(function(){
  mouseIsDown = true;
  tomove();
});
$(document).mouseup(function(){
  mouseIsDown = false;
});

Upvotes: 0

epascarello
epascarello

Reputation: 207501

You are probably better off adding the moueup on the document and not the element.

$(document).mouseup(function(){
    clearTimeout(stopmov);
});
$('.plwid').mousedown(function(){
    tomove();
});

other issue is the 1 millisecond you are using is geneterating tons of hits, you need to pick a more reasonable number.

Upvotes: 1

Related Questions