在函数javascript中访问另一个函数的超时变量

时间:2018-03-16 13:39:26

标签: javascript jquery promise

在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()

的承诺之前,我无法致电then()

3 个答案:

答案 0 :(得分:7)

您可以将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();
  })
}

答案 1 :(得分:0)

您可以将import os os.environ["password"] = "my_secret_password" 放入此类或此类函数之外的其他属性中。

timeout

答案 2 :(得分:0)

我会这样做;

var first_function  = _ => setTimeout(_ => doSomething, 300000),
    second_function = cto => hardware.open()
                                     .then(_ => clearTimeout(cto));

second_function(first_function());
相关问题