首页 > 解决方案 > 将 jQuery setInterval 计时转换为递归 setTimeout 计时

问题描述

我在这里有一个队列管理系统的代码片段,它根据允许在屏幕上显示的窗口数量从数据库中动态获取数据。

    var elementArray;

    function fetchPayment() {
        elementArray = new Array();
        $('.win_id').each(function() {
            // here's the moneyshot
            elementArray.push(this);
        });
        doAjax(0);
    }

    function doAjax(param) {
        if (typeof elementArray[param] === 'undefined') {
            var win_id = 0;
        } else {
            var win_id = elementArray[param].value;
        }
        $.ajax({
            type: "GET",
            dataType: 'json',
            //                async: false,
            url: "<?php echo base_url();?>queue/getCurrentTransaction/" + win_id,
            success: function(data) {
                param++;
                if (param <= elementArray.length) {
                    $('.names-' + win_id).empty();
                    $('.names-' + win_id).append("<div class='pname'>" + data.customer_name + '<li>' + data.ref_code + '</li></div>');
                    doAjax(param);

                } else {
                    console.log("!");
                }

            },
            error: function(data) {
                param++;
                $('.names-' + win_id).empty();
                $('.names-' + win_id).append("<div class='pname'><li></li></div>");
                doAjax(param);
            }
        });
    }

这行得通,但是,它太占用 CPU 了,而且这无疑是一种不好的方法,我重构了我的其他函数以使它们如下所示:

    (function fetchNewServiceConnection() {
        setTimeout(function() {
            $.ajax({
                type: "GET",
                dataType: 'json',
                url: "<?php echo base_url();?>queue/getCurrentTransaction/" + 100,
                success: function(data) {
                    $('.c_name').empty();
                    $('.c_name').append(data.customer_name + '<li>' + data.ref_code + '</li>');
                    fetchNewServiceConnection()
                },
                error: function(data) {
                    $('.c_name').empty();
                    $('.c_name').append('<li></li>');
                    fetchNewServiceConnection()
                }
            });
        }, 500);
    })();

这工作得更快。问题是上面的代码,我如何将它转换成下面的代码片段?

标签: phpjqueryajax

解决方案


在你的里面

function doAjax(param) {

    if (typeof elementArray[param] === 'undefined') {
        var win_id = 0;
    } else {
        var win_id = elementArray[param].value;
    }
    $.ajax({
        type: "GET",
    // etc....
        
}

你有doAjax(param);两个地方,一个用于success:,一个用于error:


doAjax(param);在这两个地方替换为:

setTimeout(doAjax.bind(null, param), 500);


注意:
我不确定,但看起来你正在尝试这样做"real time data",所以我的建议是查看WebSockets https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API),托管您自己的,或者最终托管像 Pusher.com ( https://pusher.com/ )


推荐阅读