Javascript函数正确工作8次,然后每隔一次

Javascript function works correctly 8 times, then every other time

本文关键字:一次 然后 函数 工作 8次 Javascript      更新时间:2023-09-26

我有一个javascript函数,我试图添加到我的文档,给它一种实时更新的感觉。它是对MVC控制器的AJAX调用,它返回一个JSON结果并将其添加到顶部的列表中,然后隐藏最后一个li,然后删除最后一个li。

问题是,这个功能完美地工作了8次,然后就出错了。在前8次之后,该函数只隐藏列表中的最后一项,每隔一次就在顶部添加一个。因此,在前8次运行之后,我的列表每运行一次脚本就增长1 li:

下面是我的函数:

<script type="text/javascript">
    $(document).ready(function () {
        function latestBranch() {
            $.getJSON("Home/LatestWristband", null, function (html) {
                var showHideSpeed = 200;
                var firstLI = $("#recentBranches ul li").first();
                if (firstLI.text() !== html) {
                    firstLI.before('<li>' + html + '<'li>');
                    $("#recentBranches ul li").first().hide().show(showHideSpeed);
                    $("#recentBranches ul li").last().hide(showHideSpeed / 4,
                        function () {
                            $("#recentBranches ul li").last().remove();
                        });
                }
            });
        };
        setInterval(latestBranch, 500);
    });
</script>

我已经尝试了一些事情来让它工作。我的第一个想法是,这个间隔比脚本删除最后一个列表项的时间要快,但是我已经测试了这个间隔,get的间隔为5000,元素的hide/show的间隔为1000,这应该至少在下一次调用之前提供额外的3000ms。我也试过改变这个:

$("#recentBranches ul li").last().hide(showHideSpeed / 4,
                        function () {
                            $("#recentBranches ul li").last().remove();
                        });

:

$("#recentBranches ul li").last().remove();

然而,8次后我得到同样的问题。似乎在它进入这种每隔一次才工作的节奏之后,它就会无限期地保持下去。我试着四处看看,但我似乎找不到任何可以解释这些症状的东西…

您使用了错误的斜杠来关闭<li>,这意味着您实际上为每个请求添加了2个<li>。(第二个为空白)

改变这一行:

firstLI.before('<li>' + html + '<'li>');

:

firstLI.before('<li>' + html + '</li>');