我有一个名为 particleAppear
的 JS 函数,它是一个循环:
var particles = new Array("pt0","pt1","pt2","pt3");
function particleAppear(){
var genPoint = Math.floor(Math.random() * (720 - 4 + 1)) + 4;
var particle = particles[Math.floor(Math.random()*particles.length)];
$('#particles').append('<div class="'+particle+'" style="position: absolute; top: '+genPoint+'px; left: -4px"></div>');
var rtime1 = Math.floor(Math.random() * (42000 - 32000 + 1)) + 32000;
var rtime2 = Math.floor(Math.random() * (42000 - 32000 + 1)) + 32000;
var rtime3 = Math.floor(Math.random() * (42000 - 32000 + 1)) + 32000;
var rtime4 = Math.floor(Math.random() * (42000 - 32000 + 1)) + 32000;
$('.pt0').animate({left: '+=1280px'}, rtime1, "linear",function(){
$(this).remove();
});
$('.pt1').animate({left: '+=1280px'}, rtime2, "linear",function(){
$(this).remove();
});
$('.pt2').animate({left: '+=1280px'}, rtime3, "linear",function(){
$(this).remove();
});
$('.pt3').animate({left: '+=1280px'}, rtime4, "linear",function(){
$(this).remove();
});
var randomTimeGen = Math.floor(Math.random() * (1500 - 450 + 1)) + 450;
setTimeout(particleAppear,randomTimeGen);
}
如您所见,使用的循环不是 setInterval 而是 setTimeout,它会在 450 到 1500 毫秒之间的随机时间后重新运行该函数。我怎样才能使用 JAVASCRIPT/JQUERY 停止它?
最佳答案
您可以将超时的数字 id 存储在变量中并清除它:
var timeout = setTimeout(particleAppear,randomTimeGen);
clearTimeout(timeout);
关于javascript - 无间隔停止函数循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29518671/