将新函数对象添加到数组然后调用函数方法

时间:2013-09-17 23:56:57

标签: javascript arrays function pointers settimeout

我不确定我是否在问题中使用了正确的术语,但我在playSequence()函数和setTimeOutFunction中使用循环触发了一系列定时函数调用。这很有用,但后来我想要一个暂停功能,暂停所有定时器和恢复所有定时器的恢复功能。问题是当我尝试在pauseAllTimers()函数中调用函数对象的pause方法时,它会给出错误'Uncaught TypeError:Object 0没有方法'暂停'。有任何想法吗?

var timers = new Array();

function Timer(callback, delay) {
var timerId, start, remaining = delay;

this.pause = function() {
    window.clearTimeout(timerId);
    remaining -= new Date() - start;
};

this.resume = function() {
    start = new Date();
    timerId = window.setTimeout(callback, remaining);
};

this.resume();
}

function pauseAllTimers()
{
for (var timer in timers) 
{   
    timer.pause();
}
} 

function resumeAllTimers()
{
for (var timer in timers) 
{   
    timer.resume();
}
}

function playSequence()
{
var totaltimeout = 0;
for (var lesson_step_str in lesson_step) 
{
    var splitarr = lesson_step[lesson_step_str].split("|||");
    var element = splitarr[0];
    var txt = splitarr[1];
    var timeout = splitarr[2];
    totaltimeout += (timeout*1);
    console.log(totaltimeout);
    console.log(txt);

    (function(a,b){

     var timer = new Timer(function(){ displayText( a, b); }, totaltimeout * 1000);
     timers.push(timer);
  })(element, txt);

}   
}

1 个答案:

答案 0 :(得分:0)

for循环timer返回索引而不是Timer对象,所以你需要这样做:

timers[timer].pause();

以下是工作代码:

var timers = new Array();

var Timer = function (callback, delay) {
    this.timerId, this.start, this.remaining = delay;

    this.pause = function () {
        window.clearTimeout(this.timerId);
        this.remaining -= new Date() - this.start;
    };

    this.resume = function () {
        this.start = new Date();
        this.timerId = window.setTimeout(callback, this.remaining);
    };

    this.resume();
}

function pauseAllTimers() {
    for (var timer in timers) {
        timers[timer].pause();
    }
}

function resumeAllTimers() {
    for (var timer in timers) {
        timers[timer].resume();
    }
}

function playSequence() {
    var totaltimeout = 0;
    for (var i=1;i<6; i++) {    
        var txt = "this is part "+i, 
        element="#div"+i, timeout=2;
        totaltimeout += timeout;
        (function (a, b) {
            var timer = new Timer(function () {
                $("#divTxt").html(b);
            }, totaltimeout * 1000);
            timers.push(timer);
        })(element, txt);
    }
}

$(function(){
    $("#pauseAll").click(function(){
        pauseAllTimers();
    });

    $("#resumeAll").click(function(){
        resumeAllTimers();
    });

    playSequence();
});