JavaScript的setInterval的替代?

use*_*179 1 javascript jquery setinterval

我需要实时显示我的内容,但是当加载这么多东西时,它占用了很多CPU并且非常迟钝.

我的代码下面有替代品吗?

$(document).ready(function() {
    var refresh_bal = setInterval(
        function (){
            $.get('./php/get_balance.php', function(balance) {
                $('.balance').html(balance);
            });
        }, 1000);

    var refresh_total = setInterval(
        function (){
            $.get('./php/get_total_bets.php', function(total) {
                $('.total').html(total);
            });
        }, 1000);

    var refresh_profit = setInterval(
        function (){
            $.get('./php/get_profit.php', function(profit) {
                $('.profit').html(profit);
            });
        }, 1000);

    $('.haa').on('click', function() {
        var refresh_bets = setInterval(
            function (){
                $.get('./php/get_bets.php', function(bets) {
                    $('.betsTable').html(bets);
                });
            }, 1000);
    });

    var refresh_site = setInterval(function (){
        $.get('./php/get_site.php', function(site) {
            $('.siteStats').html(site);
        });
    }, 1000);

    var refresh_client = setInterval(function (){
        $.get('./php/get_client.php', function(client) {
            $('.clientShow').html(client);
        });
    }, 1000);

    var refresh_server = setInterval(function (){
        $.get('./php/get_server.php', function(server) {
            $('.serverShow').html(server);
        });
    }, 1000);

    $('.ha').on('click', function() {
        var refresh_chat = setInterval(function() {
            $.get('./php/get_chat.php', function(chats) {
                $('.chats').html(chats);
            });
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

use*_*654 8

您可以采取两项主要措施来提高代码的性能,而无需转移到websockets.

首先,更换setIntervalsetTimeout与经常性的Ajax请求的时候.这样做的原因是如果你正在使用setInterval,下一个可能会在之前完成之前发送,最终可能会使浏览器崩溃.使用setTimeout,确保在请求下一个之前完成之前的操作.

(function refreshBalance() {
    $.get('./php/get_balance.php', function(balance) {
        $('.balance').html(balance);
        setTimeout(refreshBalance,1000);
    });
})();
Run Code Online (Sandbox Code Playgroud)

接下来,将所有这些请求合并到尽可能少的请求中,最好是一个.这是因为对于您提出的每个请求,还必须重新发送标头和cookie,并且浏览器确实限制了一次可以发送到单个域的最大并发http请求数.如果达到所述限制,则ajax请求将被延迟,直到前一个请求完成.这也可以锁定浏览器.