setInterval() loop still running after clearInterval() is called

不打扰是莪最后的温柔 提交于 2019-12-12 05:49:37

问题


I know that setInterval() returns a unique ID on every loop, and that clearInterval must be called with that ID to kill the loop. I believe my code does this, yet the loop continues to run indefinitely.

var refresh = setInterval(function () {
            $.get(url, function (data) {
                success: {
                    if (data < 5) {
                        data = 5;
                    }
                    var width = data + "%";
                    $("#recalculation-progress-bar").css('width', width);

                    if (data > 99) {
                        clearInterval(refresh);
                        $("#recalculation-message").text("Recalculation complete.");
                    }
                }
            });

        }, 3000);

I have checked this in debug and clearInterval() is definitely being called and no errors are thrown. Am I doing something obviously wrong?


回答1:


1.-

data in $.get is a String by default https://api.jquery.com/jquery.get/

data = parseInt(data)

2.-

You add a second level of sync... Are you sure that this request is faster than 3000ms?

3.- If the data is > 99, the code works.

In my concern, the problem is the request is longer than 3 seconds, and you still receive connections that your previously launched.

    if (data > 99) {
        clearInterval(refresh);
        $("#recalculation-message").text("Recalculation complete.");
    } else {
    //relaunch here the connection and remove the interval
    }


来源:https://stackoverflow.com/questions/30368368/setinterval-loop-still-running-after-clearinterval-is-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!