gpt4 book ai didi

javascript - 无间隔停止函数循环

转载 作者:行者123 更新时间:2023-11-30 07:14:45 28 4
gpt4 key购买 nike

我有一个名为 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com