JavaScript 递归设置超时
JavaScript recursive setTimeout
我在 JavaScript 中定义了这个 class:
function Signal(lbl, ho, tag) {
this.lbl = lbl;
this.ho = ho;
this.tag = tag;
this.getstatus = function () {
if (this.ho) {
$.get('/get.cgi?' + this.tag + '=?0', function (data) {
console.log(data);
setTimeout(this.getstatus, 1000);
});
}
};
}
调用 getstatus 后,它应该开始使用 setTimout 调用自身,但它没有!只能用一次。
如果我使用不带 class 的函数,它会起作用!
请帮帮我。
谢谢!
问题是当定时器调用getStatus
时,方法内部的this
没有引用对象,你可以使用[=为this
传递一个自定义值14=]。另请注意,在 ajax 回调中 this
指的是 ajax 设置对象。
function Signal(lbl, ho, tag) {
this.lbl = lbl;
this.ho = ho;
this.tag = tag;
this.getstatus = function () {
if (this.ho) {
var signal = this;
$.get('/get.cgi?' + this.tag + '=?0', function (data) {
console.log(data);
setTimeout(signal.getstatus.bind(signal), 1000);
});
}
};
}
我在 JavaScript 中定义了这个 class:
function Signal(lbl, ho, tag) {
this.lbl = lbl;
this.ho = ho;
this.tag = tag;
this.getstatus = function () {
if (this.ho) {
$.get('/get.cgi?' + this.tag + '=?0', function (data) {
console.log(data);
setTimeout(this.getstatus, 1000);
});
}
};
}
调用 getstatus 后,它应该开始使用 setTimout 调用自身,但它没有!只能用一次。
如果我使用不带 class 的函数,它会起作用!
请帮帮我。
谢谢!
问题是当定时器调用getStatus
时,方法内部的this
没有引用对象,你可以使用[=为this
传递一个自定义值14=]。另请注意,在 ajax 回调中 this
指的是 ajax 设置对象。
function Signal(lbl, ho, tag) {
this.lbl = lbl;
this.ho = ho;
this.tag = tag;
this.getstatus = function () {
if (this.ho) {
var signal = this;
$.get('/get.cgi?' + this.tag + '=?0', function (data) {
console.log(data);
setTimeout(signal.getstatus.bind(signal), 1000);
});
}
};
}