无法设法在循环中入睡 [英] Can't manage to sleep inside a loop

查看:86
本文介绍了无法设法在循环中入睡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在每次循环时都暂停1 second,在其他情况下通常很容易进行类似的暂停,但是在使用循环时,似乎会变得更加困难:

I want to pause 1 second for every time it loops, it is usually easy to do similar pauses on other cases, but when working with loops, it seems it get harder:

for (var i=0 ; i < 10 ; i++) {
    document.write (i + "<br>");
    // I want to wait 1 second here
}

这是我数千次尝试失败的例子:

This is one example of my thousands failed attempts:

function writeMsg (index) {
    document.write (index + "<br>");
}

for (var i=0 ; i < 10 ; i++) {
    setTimeout (writeMsg(i), 1000);
}

关于如何使它起作用的任何想法?

Any ideas of how to get this to work?

推荐答案

此函数的工作原理更像是普通的for循环

This function works more like a normal for loop while it isn't

您需要考虑到for for在分号之间获取3个参数.

You need to take into account that a for gets 3 arguments inbetween semicolons.

  1. 开始之前(即,定义一个var i=0变量)
  2. 再次运行代码之前的条件(例如,当我不到10岁时是i < 10)
  3. 每次执行操作时都会再次完成代码(i++向i添加一个)
  1. Before starting (ie var i=0 you define a variable)
  2. A condition before running the code again (ie i < 10 while i is under 10)
  3. An action everytime it finishes the code again (i++ add one to i)

代码

(function() {
    // Define a variable
    var i = 0,
        action = function() {
            // Condition to run again
            if (i < 10) {
                document.write(i + "<br>");

                // Add one to i
                i++;
                setTimeout(action, 1000);
            }
        };

    setTimeout(action, 1000);
})();

以下是此代码的jsfiddle,展示了其工作原理: http://jsfiddle.net/sg3s/n9BNQ/

Here is a jsfiddle for this code demonstrating its working: http://jsfiddle.net/sg3s/n9BNQ/

这篇关于无法设法在循环中入睡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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