Reputation: 449
As the subject, how can I set timeout for below jQuery?? Thank you
$(document).ready(function(){
animateM();
});
function newPosition(){
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateM(){
var newq = newPosition();
$('.animateM').animate({ top: newq[0], left: newq[1] }, function(){
animateM();
});
};
Upvotes: 0
Views: 805
Reputation: 730
Try This
$(document).ready(function(){
var newq = newPosition();
$(".animateM").animate({left:newq[1]}, "2000")
.animate({top:newq[0]}, "5000");
});
function newPosition(){
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="animateM" style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
Upvotes: 0
Reputation: 820
In a basic scenario, the preferred, cross-browser way to pass parameters to a callback executed by setTimeout
is by using an anonymous function as the first argument.:
function newPosition(){
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
$(document).ready(function(){
var newq = newPosition();
setTimeout(function() {
$('.animateM').animate({
top: newq[0],
left: newq[1],
});
, 2000 ); // 2000 is duration
});
Upvotes: 1