通过另一个函数访问动态数组中的值

时间:2012-10-23 23:41:56

标签: javascript

我有一个设置setTimeout个函数的函数。所有函数都添加到数组funcs;尽管如此,当我尝试使用stopplay().clearTimeout来阻止它们时,数组没有值。

如何访问这些功能并在其上clearTimeout

var funcs = new Array();    

function playWithDelay(){   
    for (var i = 0; i < PlayDatesArray.length; i++) { 
        funcs[i] = createfunc(i); 
    } 

    for (var j = 0; j < PlayDatesArray.length; j++) { 
        funcs[j]();
    } 
}

function createfunc(i) { 
    return function() {        
        setTimeout(function(){            
        //my function
      }, i*1500);        
    }; 
}

function stopplay(){    
    alert(this.funcs.count);
    for (var i = 0; i< funcs.count; i++){ 
        //things I tried
        var tmpFunction = funcs[i]; 
        //funcs[i].splice(i, 1);
        clearTimeout(tmpFunction);
        clearTimeout(funcs[i]);
        funcs[i]=tmpFunction;
    }    
}

2 个答案:

答案 0 :(得分:3)

clearTimeout获取setTimeout返回的ID,而不是对函数本身的引用。

所以你想要的是(在ES5代码中)

var timeouts = [];

function createfunc(i) { 
  return function() {        
      return setTimeout(function(){            
      //my function
    }, i*1500);        
  }; 
}

// code to create the functions
function playWithDelay(){   
  for (var i = 0; i < PlayDatesArray.length; i++) { 
    timeouts.push(createfunc(i)());
  }
} 


// code to stop them
function stopplay(){ 
  timeouts.forEach(clearTimeout);
}

答案 1 :(得分:1)

您正在从this.funcs访问stopplay(),但funcs已定义(至少在此示例中)为全局变量。根据调用stopplay()的调用代码,this与创建funcs的全局范围不同。

更新停止播放,将this.funcs.count更改为funcs以查看是否使用您在上面创建的阵列收到提醒。

另外,你确定你的funcs数组有count吗?我会尝试使用length代替。

function stopplay(){    
    alert(funcs.length);
    for (var i = 0; i< funcs.length; i++){ 
    ....
    }    
}

编辑:

您没有保存setTimeout的返回值,因此您无法清除超时。使用函数传递clearTimeout不会清除超时。

你可以这样做:

var timers = new Array();


function createfunc(i) { 
   return function() {        
      timers.push( setTimeout(function(){            
        //my function
      }, i*1500)) ;        
   }; 
}


function stopplay(){    
    for (var i = 0; i< timers.length; i++){ 
        clearTimeout(timers[i]);
    }    
}
相关问题