Loop every five seconds in Javascript

一笑奈何 提交于 2020-07-18 07:18:52

问题


I'm trying to write a simple loop in JS (or JQuery) that updates an image every five seconds, for a total of 15 seconds (so three loops), and then quits.

It should go like this:

  1. Wait five seconds
  2. Execute
  3. Wait five seconds
  4. Execute
  5. Wait five seconds
  6. Execute
  7. Quit

But setTimeout only seems to work once.

As a test, I've tried:

function doSetTimeout(i) {
  setTimeout(function() { alert(i); }, 5000);
}

for (var i = 1; i <= 5; ++i)
  doSetTimeout(i);

Does not work: http://jsfiddle.net/ubruksco/

I've also tried:

for(var i = 1; i <= 5; i++) {
    (function(index) {
        setTimeout(function() { alert(index); }, 5000);
    })(i);
}

Does not work: http://jsfiddle.net/Ljr9fq88/


回答1:


var time = 1;

var interval = setInterval(function() { 
   if (time <= 3) { 
      alert(time);
      time++;
   }
   else { 
      clearInterval(interval);
   }
}, 5000);

you can simply create an interval and kill it after the 3rd time




回答2:


The reason is that your settimeout ends all at the same time (after 5 seconds) because your timeout code is based on 5 seconds

for(var i = 1; i <= 5; i++) {
    (function(index) {
        setTimeout(function() { alert(index); }, 5000);
    })(i);
}

What you want to do is change the timeout time based on your index (hence will have different start times.

for(var i = 0; i < 3; i++) {
    (function(index) {
        setTimeout(function() { alert(index); }, index*5000);
    })(i);
}

(Also needs 3 iterations, so edited out the loop for you)




回答3:


Your first example is nearly there. You just need to multiply the time delay by the loop index to get the right delay.

function doSetTimeout(i) {
  setTimeout(function() { alert(i); }, 5000*i);
}

for (var i = 1; i <= 3; ++i)
  doSetTimeout(i);

http://jsfiddle.net/ubruksco/3/




回答4:


Make it easy! You do not need loop, you just need three executions.

setTimeout(function() { alert(1); }, 5000);
setTimeout(function() { alert(2); }, 10000);
setTimeout(function() { alert(3); }, 15000);

But, if you really want a loop:

function doSetTimeout(i) {
    setTimeout(function() { alert(i); }, i*5000);
}
for (var i = 1; i <= 3; ++i)
    doSetTimeout(i);



回答5:


You want setInterval() instead

 setInterval(function(){ alert("Do Something"); }, 3000);



回答6:


Assuming your are using jQuery (to manipulate the DOM),

you can try this:

['img1.jpg', 'img2.jpg', 'img3.jpg'].forEach(function(imgPath, index) {
    // the callback will be executed in 5seconds * (index + 1)
    setTimeout(function() {
       // change image source
       $('img#myImage').attr('src', imgPath);
    }, 5000 * (index + 1));
});



回答7:


With setTimeout:

function doSetTimeout(i) {
    if(i >= 3) return;
    alert(i);
    setTimeout((function () {
        return function () {
            doSetTimeout(i);
        };
    })(i + 1), 5000);
}

doSetTimeout(0);

But you can also use setInterval, maybe more appropriate.




回答8:


You can use setInterval instead and track how much times you have executed function. Than just use clearInterval() to stop execution.

var i = 1;
var interval = setInterval(function() {
  execute();
}, 5000);

$(document).ready(function() {
  execute();
});

function execute() {
  $("#output").append("set<br/>");

  if (i == 3) {
    clearInterval(interval);
  }
  i++;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output'></div>

If you want to first wait 5 secs, don't call execute() on domready.



来源:https://stackoverflow.com/questions/28697839/loop-every-five-seconds-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!