[英]Accessing a timeout variable of another function inside a function javascript
在javascript中,我正在做這樣的事情
first_function: function() {
var timeout = setTimeout(function() {
// doing something
}, 300000);
},
在另一個函數中,在做了重要的事情后,我必須訪問timeout
變量並清除超時。
second_function : function () {
// after opening the hardware, have to cleartimeout from first_function
hardware.open().then(function() {
clearTimeout(timeout);
}
// calling first_function only after hardware open
this.first_function();
但是,我得到未定義的變量timeout
,我該如何解決這個問題呢?
在解決this.first_function()
的promise之前,我無法調用this.first_function()
then()
您可以將timeout
變量存儲為另一個屬性,例如this.timeout
:
first_function: function() {
this.timeout = setTimeout(function() {
// doing something
}, 300000);
},
second_function: function() {
// after opening the hardware, have to cleartimeout from first_function
hardware.open().then(() => {
clearTimeout(this.timeout);
// calling first_function only after hardware open
this.first_function();
})
}
你可以把timeout
放在另一個屬性中,比如你的函數或者你的函數之外。
var timeout;
first_function: function() {
timeout = setTimeout(function() {
// doing something
}, 300000);
},
second_function: function() {
// after opening the hardware, have to cleartimeout from first_function
hardware.open().then(() => {
clearTimeout(timeout);
// calling first_function only after hardware open
this.first_function();
})
}
我會這樣做;
var first_function = _ => setTimeout(_ => doSomething, 300000),
second_function = cto => hardware.open()
.then(_ => clearTimeout(cto));
second_function(first_function());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.