Javascript - 通过将name变量作为参数

时间:2018-03-07 11:30:18

标签: javascript

我有一系列的计时器,我需要在我的应用程序的某些点重置。这里不存在定时器本身是不同的,因此不需要分解,但重置它们的各种功能完全相同,除了要重置的定时器的名称。

function resetMyFirstTimer() {
    if (window.myFirstTimer) {
      console.log("reset any potential prexisting myFirstTimer timer");
      clearTimeout(window.myFirstTimer);
    }
  }
function resetMySecondTimer() {
    if (window.mySecondTimer) {
      console.log("reset any potential prexisting mySecondTimer timer");
      clearTimeout(window.mySecondTimer);
    }
  }
function resetMyThirdTimer() {
    if (window.myThirdTimer) {
      console.log("reset any potential prexisting myThirdTimer timer");
      clearTimeout(window.myThirdTimer);
    }
  }
function resetMyFourthTimer() {
    if (window.myFourthTimer) {
      console.log("reset any potential prexisting myFourthTimer timer");
      clearTimeout(window.myFourthTimer);
    }
  }
and so on...

我创建了一个创建它们的函数,然后用这个函数调用它们:

function resetTimer(timerName) {
    if (window.timerName) {
      console.log("reset any potential prexisting " + timerName + " timer");
      clearTimeout(window.timerName);
    }
  }

我的问题是如何调用它们。这不起作用。我想这样做:

resetTimer(myFirstimer);
resetTimer(mySecondtimer);
resetTimer(myThirdimer);
resetTimer(myFourthTimer);
  • 如果我使用

    resetTimer(myFirstimer);

我没有定义myFirstTimer

  • 如果我使用

resetTimer("myFirstimer"); 我测试并发出警报(window.myFirstTimer)将发送未定义的

这就是我定义myFirstTimer

的方法
window.myFirstTimer = setTimeout(showAlert, 10000);

function showAlert() {
//do stuff
}

那么如何为不同的计时器名称调用它们呢?

1 个答案:

答案 0 :(得分:2)

您可以使用括号表示法引用全局变量(窗口对象)。这是一个例子......



function showVar(varName) {
    console.log(window[varName]);
}

window.someVar = "Hello there"; // create global var
showVar("someVar");             // reference global var by name




在您的方案中实施起来非常简单。将您的功能更改为此...

function resetTimer(timerName) {
    if (!window[timerName]) {
        console.log("reset any potential prexisting " + timerName + " timer");
        clearTimeout(window[timerName]);
    }
}

resetTimer("myFirstTimer");

但是,您只需将超时ID传递给函数即可。这意味着您不能像以前那样引用超时名称,但更有意义......

function resetTimer(timeoutId) {
    clearTimeout(timeoutId);
    // anything else you want to do when you cancel a timeout
}

resetTimer(window.myFirstTimer);