我注意到,我的setInterval函數從1開始計數,有時甚至從10開始計數。但是如果我將間隔增加到大約20秒,它將從0開始正確計數。隨後計數是正確的 - 在每一步中增加一個,但最初的cnt
值,如果我減少到約5秒的內部錯誤,就會出錯。javascript,setInterval函數從0開始計數
var stepProt = function() {
console.log('started stepProt constructor');
this.step = 20; //seconds
this.cnt = 0; //init counter, pointer to rtArr
};
stepProt.prototype.countingFnc = function() {
console.log('started stepFnc.prototype.countingFnc');
var msec = this.step*1000;
var that = this;
that.cnt=0;
this.nameToStop = window.setInterval(function() {
that.stepFnc(); }, msec);
}
stepProt.prototype.stepFnc = function() {
console.log (' 132 startedFnc rtG.prototype.stepFnc, this.cnt='+this.cnt); //if interval is 5seconds, this.cnt usually starts from 1, but sometimes from 10, instead of starting from 0. All other steps are correct, +1 each time.
/* here there is some logics, which takes time */
this.cnt++;
};
var stepIn = new stepProt(); //instance
stepIn.stepFnc();
可能是什麼原因以及如何解決?
p.s.其實,我在window onload之前使用這個函數。也許這是原因? 我在window.onload之前包含了很多腳本。 後來我爲window.onload功能製作了單個腳本。
我把
var stepIn = new stepFnc(); //instance
stepIn.stepFnc();
窗口的onload之前,因爲如果我在window.onload使用它,因爲某些原因,其它功能並不瞭解stepIn
實例作爲一個全局變量accessable everythere。也許這是因爲我使用php模板。
你能爲這兩種情況提供一個片段嗎?運行你的代碼並改變'this.step = 5; // seconds'似乎對結果沒有影響 –
您的代碼顯示輸出'開始stepFnc構造函數',然後'132 startedFnc rtG.prototype.stepFnc,this.cnt = 0' - 並且什麼都不做 –
但是,您將代碼的最後一行更改爲'stepIn.countingFnc();'(這實際上是有意義的,因爲那是間隔開始的位置),然後在20秒後,'132 startedFnc rtG.prototype.stepFnc,this.cnt = 0'輸出,然後又一個20秒'132啓動Fnc rtG.prototype.stepFnc,這個。cnt = 1'等 - 當你以你應該的方式運行你的代碼時,你觀察到了什麼? –