JavaScript:如何防止setInterval触发多线程

时间:2013-07-09 14:30:55

标签: javascript singleton

我想创建一个计时器,在每X秒后,应该发生一个请求;

在X秒后发出请求,但如果我停止计时器然后重新启动它,我认为我得到2个执行线程,因为每次我停止并重新启动计时器时请求变得更快;

我该如何解决这个问题?

<script>
    var SingletonClass = SingletonClass ? SingletonClass : function() {
        var apiUrl = '<?php echo Yii::app()->baseUrl; ?>';
        var int;
        var offset;
        var reset_time_in_secconds = 1;
        var f = function()
        {

        };
        f.prototype = {
            fnAddRow: function(data) {
                offset = data.created;
                $('#example').dataTable().fnAddData([
                    data.id + '.0',
                    data.type + ".1",
                    data.level + ".2",
                    data.msg + ".3",
                    data.code + ".4",
                    data.created + ".5"]);
            },
            clockTick: function()
            {
                console.log('clock tick');
                example_length_value = $('select[name="example_length"]').val();
                $.ajax({
                    type: "POST",
                    url: '<?php echo Yii::app()->baseUrl; ?>' + '/index.php/admin/liveReports/inputNotificationLog/offset/' + offset + '/pageSize/' + example_length_value,
                    data: {'offset': offset, 'pageSize': example_length_value},
                    success: function(data) {
                        //console.log(data);
                        //$('.input').text(data);
                        if (data.length > 0)
                        {
                            $.each(data, function(index, value) {
                                //console.log(value);
                                //console.log(data[index]);
                                obj = value;
                                Singleton.fnAddRow(obj);
                            });
                        }
                    },
                    dataType: 'json'
                });
            },
            stopClock: function()
            {
                console.log('stop clock');
                int = window.clearInterval(int);
            },
            init: function()
            {
                console.log('init');
                offset = <?php echo time(); ?>;
                reset_time_in_secconds = $('#reset_time_in_secconds').val();
                if (reset_time_in_secconds == '') {
                    reset_time_in_secconds = 1;
                }
                $('#demo').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>');
                $('#example').DataTable({
                    "aaData": [
                        /* Reduced data set */
                        /* ["1", "Trident", "Internet Explorer 4.0", "Win 95+", 4, "X"], */
                    ],
                    "aaSorting": [[0, "desc"]],
                    "aoColumns": [
                        {"sTitle": "id"} /* { "bSearchable": false, "bVisible":    false } */,
                        {"sTitle": "type"},
                        {"sTitle": "level"},
                        {"sTitle": "msg"},
                        {"sTitle": "code", "sClass": "center"},
                        {
                            "sTitle": "created",
                            "sClass": "center",
                            "fnRender": function(obj) {
                                var sReturn = obj.aData[ obj.iDataColumn ];
                                if (sReturn == "A") {
                                    sReturn = "<b>A</b>";
                                }
                                return sReturn;
                            }
                        },
                    ]
                });
                int = setInterval(Singleton.clockTick, reset_time_in_secconds * 1000);
            },                    
            reinit: function()
            {
                Singleton.stopClock;
                console.log('reinit');
                offset = <?php echo time(); ?>;
                reset_time_in_secconds = $('#reset_time_in_secconds').val();
                if (reset_time_in_secconds == '') {
                    reset_time_in_secconds = 1;
                }
                int = setInterval(Singleton.clockTick, reset_time_in_secconds * 1000);
            },
            restartClock: function()
            {
                console.log('restart clock');
                Singleton.reinit();
            },
            inBound: function(action, data)
            {
                try {
                    console.log('inbound');
                    switch (action)
                    {
                        case 'actiune':
                            console.log('actiune');
                            break;
                        default:
                            alert('Unknown inBound action: ' + action);
                            break;
                    }
                } catch (err) {
                    if (consoleLog) {
                        //console.log(err.toString());
                    }
                    alert('Something went wrong, server returned invalid message!');
                }
            }, //end f inBound()
            outBound: function(action)
            {
                try {
                    switch (action)
                    {//start switch
                        case 'logout':
                            //ceva
                            break;
                        default:
                            alert('Unknown outBound action: ' + action);
                            break;
                    }//end switch
                }
                catch (err) {
                    if (consoleLog) {
                        //console.log(err.toString());
                    }
                    alert('Something went wrong, couldn\'t prepare data!');
                }


            }//end f outBound()
        }
        return f;
    }();
    var Singleton = new SingletonClass();
    Singleton.init();
</script>

1 个答案:

答案 0 :(得分:0)

解决了问题;

我在使用指针而不是方法时,在启动时使用:函数Singleton.stopClock而不是Singleton.stopClock();