0

我不确定我是否在问题中使用了正确的术语,但我使用 playSequence() 函数和 setTimeOutFunction 中的循环触发了一系列定时函数调用。这很有效,但是我想要一个暂停功能来暂停所有计时器和一个恢复功能来恢复所有计时器。问题是,当我尝试在 pauseAllTimers() 函数中调用函数对象的暂停方法时,它会给出错误“未捕获的类型错误:对象 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);

}   
}
4

1 回答 1

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();
});
于 2013-09-18T01:09:12.457 回答