如何通过引用传递超时?或者更好的实施方式

How to pass timeout by reference? Or a better way to implement?

本文关键字:更好 方式 或者 引用 何通过 超时      更新时间:2023-09-26

我以前使用过这段代码,但现在我不太确定我是否已经将HTML控件与jQueryUI Widget分离。

目前,计时器启动正确,但在一次勾选后,我失去了对_refreshTimeout的引用。也就是说,在第一次勾选后,取消勾选PlanViewRefresh复选框不会停止计时器的运行。

我有两个JavaScript文件,PlanView.js和PlanViewCanvas.js。

PlanView.js看起来像这样:

(function ($) {
    var _minZoom = -2.0;
    var _maxZoom = 2.0;
    var _stepZoom = (_maxZoom - _minZoom) / 100;
    var _refreshTimeout = null;
    var _refreshInterval = 60000; //One minute
    $(document).ready(function () {
        //Initialize Refresh combo box.
        $('#PlanViewRefreshCheckbox').click(function () {
            if ($(this).is(':checked')) {
                var planViewCanvas = $('#PlanViewCanvas');
                //Binding forces the scope to stay as 'this' instead of the domWindow (which calls setTimeout).
                _refreshTimeout = setTimeout(function(){planViewCanvas.PlanViewCanvas('refresh', _refreshInterval, _refreshTimeout)}.bind(planViewCanvas), _refreshInterval)
            }
            else {
                clearTimeout(_refreshTimeout);
            }
        });
    }
})(jQuery);

PlanViewCanvas.js包含一个jQueryUI小部件:

(function ($) {
    $.widget("ui.PlanViewCanvas", {
        //other properties and methods not-relevant to problem declared here.
        refresh: function (refreshInterval, refreshTimeout) {
            var self = this;
            _stage.removeChildren();
            self.initialize();
            //Binding forces the scope to stay as 'this' instead of the domWindow (which calls setTimeout).
            refreshTimeout = setTimeout(function () { self.refresh(refreshInterval, refreshTimeout) }.bind(self), refreshInterval);
        },
    }
})(jQuery);

看起来我做事情不对吗?

编辑:我认为答案可能是使用setInterval而不是setTimeout。

第一个问题是您忘记了下划线

refreshTimeout应为_refreshTimeout

其次,您的变量需要是全局的,才能在两个文件中访问,所以在函数之外声明它:

var _minZoom = -2.0;
var _maxZoom = 2.0;
var _stepZoom = (_maxZoom - _minZoom) / 100;
var _refreshTimeout = null;
var _refreshInterval = 60000; //One minute
(function ($) {
   ....
})(jQuery)

不能通过引用传递值。我看到两个选项:

  • 传递对象。如果从两个变量引用它,则可以在两个作用域中访问它的属性
  • 将您的功能划分为两个函数,它属于两个函数:一个负责间隔循环并触发刷新函数,另一个负责刷新。refreshTimeout变量只属于第一个变量的范围。指向如果经常需要,您可以将interval函数添加到小部件中

答案非常"哦,derp"

    //Initialize Refresh combo box.
    $('#PlanViewRefreshCheckbox').click(function () {
        if (this.checked) {
            _refreshTimeout = setInterval(function(){$('#PlanViewCanvas').PlanViewCanvas('refresh')}, _refreshInterval)
        }
        else {
            clearTimeout(_refreshTimeout);
        }
    });