jQuery/JS无限定时循环

jQuery/JS infinite timed loop

本文关键字:定时 循环 无限 JS jQuery      更新时间:2023-09-26

我试图在不同时间在屏幕上的不同元素上创建一系列点击。我可以很容易地做到这一点,使用setTimeout函数,但我需要使这一个无限循环!?

下面是我目前如何处理代码的一个片段。

setTimeout(function () {jQuery('.CR_1').trigger('click');}, 1000);
setTimeout(function () {jQuery('.CR_1').trigger('click');}, 5000);
setTimeout(function () {jQuery('.CR_2').trigger('click');}, 5500);

有什么好主意吗?

编辑:让我更清楚一点。我试着一遍又一遍地以相同的顺序运行函数集。setInterval工作得很好。很抱歉给你造成了任何困惑。

   setInterval ( "flips ()", 12000 );

function flips (){
    setTimeout(function () {jQuery('.CR_1').trigger('click');}, 1000);
    setTimeout(function () {jQuery('.CR_1').trigger('click');}, 5000);
    setTimeout(function () {jQuery('.CR_2').trigger('click');}, 5500);
    }

从函数中调用setTimeout

setTimeout(callMe, 1000);
function callMe() {
    jQuery('.CR_1').trigger('click');
    setTimeout(callMe, 1000);
}

您也可以使用setInterval,但我更喜欢这样做,因为它将在上次运行后1000毫秒被调用,而不是每1000毫秒调用一次,无论运行多长时间(如果进程是同步的)。

clicky()
function clicky() {
   setTimeout(function () {jQuery('.CR_1').trigger('click');}, 1000);
   setTimeout(function () {jQuery('.CR_1').trigger('click');}, 5000);
   setTimeout(function () {jQuery('.CR_2').trigger('click');clicky()}, 5500);
}

我认为你应该用setInterval而不是setTimeout

为什么不使用setInterval呢?

var delayedFunctions = [
  [1000,function(){ ... }],
  [5000,function(){ ... }],
  [5500,function(){ ... }]
];
var fIndex = 0;
function runDelayedFunctions(){
  var details = delayedFunctions[fIndex];
  setTimeout( function(){
    details[1].call(this);
    if (++fIndex >= delayedFunctions.length) fIndex=0;
    runDelayedFunctions();
  }, details[0] );
};
runDelayedFunctions();