-->

setInterval() loop still running after clearInterv

2019-09-09 21:57发布

问题:

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
    }