为什么一切都在Javascript中使用setTimeout显示? [英] Why does everything display at once, using setTimeout in Javascript?

查看:112
本文介绍了为什么一切都在Javascript中使用setTimeout显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在javascript中向下滚动一些内容,但是,在执行时,它只是说了一下并立即显示所有内容。所以它不是用 $(#Menu)清除.html('')函数和 setTimeout(函数{},500)只是为整个页面而不是代码段设置超时。

I'm trying to make a few things scroll down the screen in javascript, however, upon execution, it just says a little and displays everything at once. So it's not clearing with the $("#Menu").html('') function and the setTimeout(function {},500) is just setting a timeout for the entire page instead of the code segment.

var MenuData = [
{'Name':'pictures','x':'30'},
{'Name':'blog','x':'50'},
{'Name':'contact','x':'42'}
]
;  


var PositionArray = new Array();
$(document).ready(function () {
    for (var count = 0; count < 1000; count++) {
        $("#Menu").html('');
        if (PositionArray[count] != null) {
            PositionArray[count]++;
        } else {
            PositionArray[count] = 0;
        }

        setTimeout(function () {
        for (var i in MenuData) {
                $("#Menu").append('<div style="position:relative; left:' + MenuData[i].x + 'px; top:' + PositionArray[i] + 'px; ">123</div>');
            }
        }, 500);

    }
});

这是小提琴: http://jsfiddle.net/LbjUP/

编辑:代码中有一点点错误没有适用于这个问题。这是新的: http://jsfiddle.net/LbjUP/1/ ,我刚刚移动了PositionArray [count]到setTimeout函数作为PositionArray [i]

There was a little bit of error in the code that doesn't apply to the question. Here's the new one: http://jsfiddle.net/LbjUP/1/, I just moved PositionArray[count] to the setTimeout function as PositionArray[i]

推荐答案

如评论中所述,您正在为500创建1000个超时ms同时 - 在500毫秒后,所有这些都将被执行。你想要的是增加每个预定函数的超时:

As stated in the comments, you are creating 1000 timeouts for 500 ms at the same time - after 500 ms all of them will be executed. What you want is to increase the timeout for every scheduled function:

setTimeout(function() {
    // do something
}, count * 500);

但是,一次创建1000个超时并不是一个好主意。最好使用 setInterval 或者递归地调用 setTimeout ,直到达到1000的计数,这样你就可以了一次只有一个活动超时。

However, creating 1000 timeouts at once is not a that good idea. It would be better to use setInterval or call setTimeout "recursively" until a count of 1000 is reached, so that you only have one active timeout at a time.

var count = 0;
function update() {
    // do something
    if (++count < 1000)
        setTimeout(update, 500);
    // else everything is done
}
update();

此外,如果您打算在循环中创建超时,请确保熟悉闭包及其在循环运行后访问计数器变量时的行为。

Also, if you intend to create timeouts in a loop, be sure to be familiar with closures and their behavior when accessing counter variables after the loop ran.

这篇关于为什么一切都在Javascript中使用setTimeout显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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