0

有人可以帮我纠正与 相关的问题setInterval吗?我对 JavaScript 很陌生,我不确定这里有什么问题。我的页面中有这个块:

GlobalTicker.prototype.TickElements = function () {
    this.timer = setInterval(this.initializeElement.apply(this) , 1000);
};
GlobalTicker.prototype.initializeElement = function () {
    for (var i = 0; i < this.tickerElements.length; i++) {
        var existingRun = this.tickerElements[i].secs;
        var elementId = $('#' + this.tickerElements[i].id + ' .comment-editor').find('.ticker');
        existingRun -= 1;
        $(elementId).text(existingRun);
        if (existingRun === 0) {
            $(elementId).remove();
            this.tickerElements.splice(i, 1);
            if (this.tickerElements.length == 0) clearInterval(this.tickerElements.timer);
        }
    }
};

然后在代码的某个地方,我在一个函数中有这个调用

var objTicker = new GlobalTicker();
CommentManagement.prototype.createComment = function (domObject) {
    objTicker.TickElements();
};

这个函数调用实际上调用setInterval函数并运行第一次迭代并跳转到,initialiseComment();但是一旦这个块被执行,在下一个间隔,而不是initialiseComment();再次执行,它跳回到我的函数调用CreateComment();。我在这里做错了什么?

4

1 回答 1

3

setInterval() requires a function reference. You were calling the function itself and passing the return result from executing the function (which was undefined) to setInterval(). Since that return value is not a function, there was no callback function for setInterval() to call. Thus, your method was executed once when you first called it, but couldn't be called by the interval.

To fix it, you should change from this:

this.timer = setInterval(this.initializeElement.apply(this) , 1000);

to this:

var self = this;
this.timer = setInterval(function() {self.initializeElement()}, 1000);

Note, the value of this will also be different in the setInterval() callback than the value you want so the one you want is saved here in self so it can be referenced from that. There's also no need to use .apply() in this case because calling a method on an object will automatically set the this pointer as needed.

于 2013-03-29T21:31:04.333 回答