倒计时计时器对象-Javascript

倒计时计时器对象-Javascript,javascript,object,counter,Javascript,Object,Counter,我想用Javascript创建一个简单的计时器,从给定时间开始倒计时,直到达到0。我发现这个很好用。我的问题是,我需要在同一页上放置多个计时器。本教程显然不会这样做,因为它使用全局变量(我是JS/编程新手,所以可能没有使用正确的术语)。我试图重新创建相同的东西,只创建每个计时器作为它自己的对象,这样它们就不会相互干扰。这就是我所拥有的 function taskTimer(name, startTime) { this.timer = name; this.totalSeconds =

我想用Javascript创建一个简单的计时器,从给定时间开始倒计时,直到达到0。我发现这个很好用。我的问题是,我需要在同一页上放置多个计时器。本教程显然不会这样做,因为它使用全局变量(我是JS/编程新手,所以可能没有使用正确的术语)。我试图重新创建相同的东西,只创建每个计时器作为它自己的对象,这样它们就不会相互干扰。这就是我所拥有的

function taskTimer(name, startTime) {
  this.timer = name;
  this.totalSeconds = startTime;
  this.tick = function() {
    if (this.totalSeconds <= 0) {
      return;
    }
    this.totalSeconds -= 1;
    this.updateTimer();
    // window.setTimeout("this.tick()", 1000);
  };
  this.updateTimer = function(){
    this.seconds = this.totalSeconds;

    this.hours = Math.floor(this.seconds / 3600);
    this.seconds -= this.hours * (3600);

    this.minutes = Math.floor(this.seconds / 60);
    this.seconds -= this.minutes * (60);

    this.timeString = this.leadingZero(this.hours) + ":" + this.leadingZero(this.minutes) + ":" + this.leadingZero(this.seconds);
    return this.timeString;
  };
  this.leadingZero = function(time){
    return (time < 10) ? "0" + time : + time;
  };
}
var testTimer = new taskTimer("timer", 30);
testTimer.tick();
函数任务计时器(名称、开始时间){
this.timer=名称;
this.totalSeconds=startTime;
this.tick=函数(){

如果(this.totalSeconds我总是对
this
有问题,并且在一个实例中,在函数中,我必须重新定义它:

this.tick = function() {
  self=this;
  if (self.totalSeconds <= 0) {
    return;
  }
  self.totalSeconds -= 1;
  self.updateTimer();
   // window.setTimeout("self.tick()", 1000);
};
this.tick=function(){
self=这个;

如果(self.totalSeconds您遇到了一些问题

  • 您正在
    tick
    方法内部调用
    updateTimer()
    ,因此 除非你把它还给我,否则我永远也够不到外面
  • 在当前设置下,每次需要更新时钟时,您都必须手动调用
    勾选
    ,如果不精确地每隔一秒钟进行一次,计时器将不准确
  • 对于#2,你不应该像现在这样递减
    totalSeconds
    ,因为不能保证超时触发之间的间隔正好是1秒。请改用日期
  • 下面是我要做的:


    我的版本,您可以在以下位置看到:

    var tmArray=new Array();
    var timerRef,timerId=0;
    函数newTimer(){
    试一试{
    如果(tmArray.length>4)抛出“太多计时器”;
    var countDown=parseInt(document.getElementById(“tcontown”).value,10);
    如果(isNaN(倒计时))抛出“tCountown是NaN”;
    var tmName=document.getElementById(“tName”).value;
    var nt=新任务计时器(++timerId,tmName,倒计时);
    createTmElement(timerId,tmName);
    t阵列推力(nt);
    如果(!timerRef)timerRef=setInterval(timerFn,1000);
    showTimers();
    }捕获(er){
    警报(“新定时器:+er”);
    }
    }
    函数taskTimer(id、名称、TCountDown){
    this.id=id;
    this.tName=名称;
    this.tcontown=tcontown;
    }
    函数timerFn(){
    试一试{
    var i;
    killTimer=true;
    对于(i=0;i
    事实上,在您提供的代码中不需要这个。但是当您使用回调时,比如在setTimeout或其他东西中,您确实需要它(似乎您想通过注释来突出这一点),为什么要将调用引用为tick?我认为这有点简洁:setTimeout(self.tick,1000);您正在将self声明为一个全局.tsk tsk。我之所以对它进行评论,是因为我正在测试tick方法,不希望它再次运行。这对我也不起作用,它只是冻结了。您如何判断这是否起作用?您没有在任何地方绘制任何计时器值。因为updateTimer方法起作用,所以调用tick方法should返回相同的值,因为它调用其中的updateTimer方法。“
    testTimer.tick();
    不返回值”这就是您试图解决的问题吗?如果是,该函数永远不会返回任何内容。您需要在其中使用
    return
    语句。但是testTimer.tick();调用updateTimer();方法返回一个值。这不是意味着testTimer.tick()吗;会返回相同的值吗?@smdecoto updateTimer返回一个要勾号的值,但勾号不会返回给您。还要注意,约定的类将以大写字母开头。我会努力理解这个lol。此外,我正在尝试让多个计时器同时运行。太棒了。我还不完全理解,但我会得到它:)谢谢!@SMDeConto你有什么具体的问题吗?我肯定会的,但到目前为止,我很高兴了解你使用的一些方法/语法。我刚开始上学,试图在课间休息时自己做一些独立的学习,所以我为自己创建了这个项目。我认为阅读别人的代码对我很有帮助。我会让你知道的你知道有什么我搞不懂的,谢谢!
    // I added optional callbacks. This could be setup better, but the details of that are negligible. 
    function TaskTimer(name, durationInSeconds, onEnd, onTick) {
        var endTime,
            self = this, // store a reference to this since the context of window.setTimeout is always window
            running = false;
        this.name = name;
        this.totalSeconds = durationInSeconds;
    
        var go = (function tick() {
            var now = new Date().getTime();
            if (now >= endTime) {
                if (typeof onEnd === "function") onEnd.call(self);
                return;
            }
            self.totalSeconds = Math.round((endTime - now) / 1000); // update totalSeconds placeholder
            if (typeof onTick === "function") onTick.call(self);
            window.setTimeout(tick, 1000 / 12); // you can increase the denominator for greater accuracy. 
        });
    
        // this is an instance method to start the timer
        this.start = function() {
            if (running) return; // prevent multiple calls to start
    
            running = true;
            endTime = new Date().getTime() + durationInSeconds * 1000; // this is when the timer should be done (with current functionality. If you want the ability to pause the timer, the logic would need to be updated)
            go();
        };
    }
    // no reason to make this an instance method :)
    TaskTimer.prototype.toTimeString = function() {
        var hrs = Math.floor(this.totalSeconds / 60 / 60),
            min = Math.floor(this.totalSeconds / 60 - hrs * 60),
            sec = this.totalSeconds % 60;
    
        return [hrs.padLeft("0", 2), min.padLeft("0", 2), sec.padLeft("0", 2)].join(" : ");
    };
    
    var task = new TaskTimer("task1", 30, function() {
        document.body.innerHTML = this.toTimeString();
        alert('done');
    }, function() {
        document.body.innerHTML = this.toTimeString();
    });
    
    var tmArray = new Array();
    var timerRef, timerId=0;
    
    
    function newTimer(){
        try{
            if(tmArray.length > 4) throw "Too much timers";
            var countDown = parseInt(document.getElementById("tCountown").value,10);
            if(isNaN(countDown)) throw "tCountown is NaN";
            var tmName = document.getElementById("tName").value;
            var nt = new taskTimer(++timerId, tmName, countDown);
            createTmElement(timerId, tmName);
            tmArray.push(nt);
            if(!timerRef) timerRef = setInterval(timerFn, 1000);
            showTimers();
        }catch(er){
            alert("newTimer:" + er);
        }
    }
    
    function taskTimer(id, name, tCountown) {
        this.id = id;
        this.tName = name;
        this.tCountown = tCountown;
    }
    
    
    function timerFn(){
        try{
            var i;
            killTimer = true;
            for(i = 0; i < tmArray.length; i++){
               tmArray[i].tCountown--;
                if(tmArray[i].tCountown < 0){
                    tmArray[i].tCountown = 0;
                }else{
                    killTimer = false;
                }
            }
            if(killTimer) clearInterval(timerRef);
            showTimers();
        }catch(er){
            clearInterval(timerRef);
            aler("timerFn: " + er);
        }
    }