同步setTimeout + Loop [英] Synchronous setTimeout + Loop

查看:151
本文介绍了同步setTimeout + Loop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:

我有X(0-20)图像需要按顺序显示,每个图像之间有延迟。

I have X (0-20) Images that need to be shown in order with a delay between each of them.

我试图用for-loop和setTimeout来实现它,但是却难以以同步顺序运行内码。

I tried to implement that with a for-loop and setTimeout but struggle with running the innercode in synchronous order.

例如:

for(x=0;x<20;x++) {
setTimeout(doSomething(), 5000);
}


doSomething() {
setTimeout(function() {alert("test")},1000);
}

如果我没有记错,我应该每隔6秒看一次警报,20倍。
然而,发生的事情是,在6秒后我立即看到所有警报(或者我放入doSomething的任何内容)

If I am not mistaken I should see an alert every 6 seconds, for 20 times. However, what happens is that after 6 seconds I see all the alerts at once (or whatever I put into doSomething)

我如何得到我的 - 循环等待内部代码完成?

How do I get my for-loop to wait till the innercode is completed?

推荐答案

这是JavaScript中的预期行为。你的第一个函数几乎会立即循环到结尾,而不是5000 * 20毫秒。

This is the expected behaviour in JavaScript. Your first function will loop to the end almost immediately, not in 5000*20 milliseconds.

这是你可以做的:创建一个带有setTimeout的IIFE:

This is what you can do: create a IIFE with a setTimeout inside:

var i = 0;
(function loop(){
  if (i++ > 20) return;
  setTimeout(function(){
    alert("hi");
    loop();
  }, 5000);
})();

这是小提琴:https: https://jsfiddle.net/f6ztxmgp/1/

Here is the fiddle:https: https://jsfiddle.net/f6ztxmgp/1/

您可以简单地更改 alert(hi) part to doSomething()

You can simple change the alert("hi") part to doSomething().

这篇关于同步setTimeout + Loop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆