setTimeout可以与闭包内的函数一起使用吗?

Sil*_*eth 0 javascript

JavaScript的setTimeout函数可以用于闭包内的函数吗?如果调用setTimeout是在同一个闭包内进行的,该怎么办?

通过我的尝试,似乎你不能.不过,我不确定我是否遗漏了什么.

基本上,我想这样做:

var ButtonCycler = (function() {
  var ButtonCycler = {};
  var autoCycle;
  var idx = 0;
  var buttonIds = [];
  buttonIds[0] = "id1";
  buttonIds[1] = "id2";
  //"Public" methods
  ButtonCycler.startAutoCycle = function() {
    autoCycle = true;
    cycleButtons();
  }
  ButtonCycler.stopAutoCycle = function() {
    autoCycle = false;
  }
  //Worker function (effectively private because it's in the closure)
  function cycleButtons() {
    var radioButton;
    if(autoCycle) {
      radioButton = document.getElementById(buttonIds[idx]);
      radioButton.checked = true;
      idx++;
      if(idx >= buttonIds.length) {
        idx = 0;  //Start over at first button
      }
      setTimeout('cycleButtons()',2500); //Delay for 2.5 seconds
    }
  }
  return ButtonCycler;
})(); //IIFE
Run Code Online (Sandbox Code Playgroud)

然后在onload页面中,我可以这样做:

ButtonCycler.startAutoCycle();
Run Code Online (Sandbox Code Playgroud)

当用户手动点击其中一个单选按钮时,我可以这样做:

ButtonCycler.stopAutoCycle();
Run Code Online (Sandbox Code Playgroud)

并且用于执行循环的机制可以很好地封装在封闭件中.

当我尝试这个时,我得到一个cycleButtons不存在的错误.cycleButtons尽管如此,最初的呼吁是成功的.呼叫发起的呼叫setTimeout是失败的.

KJ *_*ice 5

您将cycleButtons()作为字符串传递,稍后将使用该字符串进行调用eval.这将假设cycleButtons在全局范围内可用(它不是).相反,将引用传递给实际函数:

setTimeout(cycleButtons, 2500);
Run Code Online (Sandbox Code Playgroud)