【问题标题】:How can I set up a timed interval in javascript?如何在javascript中设置定时间隔?
【发布时间】:2010-09-20 07:34:15
【问题描述】:

以下 javascript 应该设置一个间隔,以便 json 对象列表中的新项目将缓慢添加到列表顶部,但它们会同时添加。

<script type="text/javascript">
    var json;
    var count = 0;
    $(document).ready(function() {
        $.ajax({
            type: "POST",
            url: "/Home/PublicTimeLine",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                json = eval(msg);
                createRow();
            }

        });
    });

    function createRow() {
        if (count < json.length) {
            var data = json[count];
            var row = document.createElement("div");
            $(row).hide();
            row.appendChild(document.createTextNode(data.text));
            $(document).find("#results").prepend(row);
            $(row).fadeIn("slow");
            count++;
            setTimeout(createRow(), 3000);
        }
    }
</script>

<div id="results">
</div>

【问题讨论】:

    标签: asp.net javascript jquery asp.net-mvc


    【解决方案1】:

    如果我是你,我会以稍微不同的方式解决它。为什么不将所有数据添加到您的页面上,而只是隐藏它并仅在您需要时显示。这样您就不必担心闭包之类的问题。

    var intervalId;
    $.ajax({
        type: "POST",
        url: "/Home/PublicTimeLine",
        dataType : "json",
        success : function (msg) {
            var json = eval(msg); // is this even needed?
            $.each(json, function(ind, data) {
                $("<div></div>")        // use jQuery to create the div
                    .hide()
                    .text(data)        // you can use jQuery to add contents too. (use .html() if you need HTML)
                    .prependTo('#results')
                ;
            });
            intervalId = setInterval(showRow, 3000);
        }
    });
    function showRow() {
        var $myDiv = $('#results div:hidden:last');
        if ($myDiv.length) {
            $myDiv.show('slow');
        } else {
            clearInterval(intervalId);    // none more to show, stop checking
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-09
      • 2012-08-16
      • 2020-06-21
      • 2020-12-23
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多