[英]JavaScript functions setTimeout() and setInterval() are sometimes not working
[英]JavaScript: setTimeout (setInterval) not working
好的,所以基本上我正在創建一個Interval類來處理重復的動作。 我有這樣的事情:
function Interval(fn, speed) { this.fn = fn; this.speed = speed; this.nt = setInterval(fn, speed); }
然后我有3種方法:
this.pause = function() { clearInterval(this.nt); } this.start = function() { this.nt = setInterval(this.fn, this.speed); return this.nt; } this.wait = function(time) { this.pause(); setTimeout(function() { this.start(); }, time); }
問題出現在第三種方法中。 this.pause();
和this.start();
如預期般運作。 但是,當我將this.start
嵌套到setTimeout
函數中時,它將停止工作。 我不明白為什么。 這是一個例子:
var i = 0: var nt = new Interval(function() { alert('Itineration: '+ i ); if(i>5); nt.pause(); setTimeout(nt.start, 2000); // nt.wait(2000); }, 500);
既不是nt.wait(2000);
也不是nt.pause(); setTimeout(nt.start, 2000);
nt.pause(); setTimeout(nt.start, 2000);
正在工作。
this
一次超時處理程序里面是不是Interval
對象,它指的是window對象(不嚴格模式),所以this.start()
將無法正常工作
一種解決方案是使用Function.bind()傳遞自定義上下文
this.wait = function (time) {
this.pause();
setTimeout(function () {
this.start();
}.bind(this), time);
// setTimeout(this.start.bind(this), time) as @elclanrs suggested
}
您的代碼遇到上下文問題。 當setTimeout函數執行您的回調時,“ this”的定義不再是您的Interval對象。 您需要修改代碼,以便維護對Interval對象的正確引用。
this.wait = function(time) {
var interval = this;
interval.pause();
setTimeout(function() {
interval.start();
}, time);
}
編輯
我剛剛看到了使用.bind的另一個答案,從可讀性的角度來看,這是一個更干凈的解決方案。 關於.bind一個重要的說明是,在幕后它基本上使用.CALL或。適用方法來設置這個正確的值產生另一個函數來調用原始的功能
在大多數情況下,使用.bind獲得的可讀性值得。 但是,如果這將成為大型系統的核心組件,則最好壓縮每一個性能點。 在這種特定情況下,應避免使用.bind 。
根據其他答案的工作示例。
function Interval(fn, speed) { this.fn = fn; this.speed = speed; this.nt = setInterval(fn, speed); this.pause = function () { clearInterval(this.nt); } this.start = function () { this.nt = setInterval(this.fn, this.speed); return this.nt; } this.wait = function (time) { this.pause(); setTimeout(function () { this.start(); }.bind(this), time); } } var i = 0; var nt = new Interval(function () { document.write('<pre>Itineration: ' + i + '</pre>'); i++; nt.wait(2000); }, 500);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.