javascript - 创建多个可控定时器

标签 javascript function object

我该如何将这整个事情变成一个创建新的可控计时器的函数?

var seconds = 0;
var interval;
//when you want the timer to stop
var endTime = 55;

function checkTimer() {
if (seconds == endTime) {
    restartPause();

}};

//reset timer
function restart() {
pause();
seconds = 0; interval = setInterval(function() {console.log(seconds); seconds++; checkTimer()}, 1000);
};

//pause timer
function pause() {
  clearInterval(interval);
};

//play timer
function start() {
  pause();
  interval = setInterval(function() {console.log(seconds); seconds++; checkTimer()}, 1000);
};

//Restart and Pause, for when the video ends
function restartPause() {
restart();
pause();
};

function timeChange(n) {
seconds = n;
}

假设我希望能够像这样创建多个计时器

var myTimer = new timer();
var anotherTimer = new timer();
var thirdTimer = new timer();

最佳答案

有几种方法可以做到这一点。如果您使用的浏览器可以处理 ES6 类,您可以创建一个将所有这些函数定义为方法的类。在 Javascript 中执行此操作的传统方法是定义一个函数,然后将其他函数添加到原型(prototype)中。您需要使用实例中的 this 访问变量和函数。下面是一个使用一些函数的示例,应该展示其工作原理:

function Timer(endTime){
    // define instance properties
    this.endTime = endTime;
    this.interval = undefined
    this.seconds = 0
}

// Define methods
Timer.prototype.pause = function() {
    clearInterval(this.interval);
}
Timer.prototype.start = function(){
    this.pause()
    // you should use arrow => functions when passing methods to event handler
    this.interval = setInterval(() => {console.log(this.seconds); this.seconds++; this.checkTimer()}, 1000)
}
Timer.prototype.checkTimer = function() {
    if (this.seconds >= this.endTime) {
        this.pause();
    }
};
Timer.prototype.restart = function() {
    this.seconds = 0; 
    this.start()
};

// create a timer that will stop in 10 and start it
let t = new Timer(10)
t.start()

// create another
let t2 = new Timer(10)
t2.start()

// stop the second one in a few seconds
setTimeout(() => t2.pause(), 3100)

请注意,计时器不是很准确,因此如果您需要精确时间的东西,您可能需要寻找不同的方法。

关于javascript - 创建多个可控定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51587795/

相关文章:

javascript - React Router - 未捕获的语法错误 : Unexpected token < when refreshing an URL with params

c++ - static const 对象不保留值

c - 为什么函数不应该返回本地数组?

javascript - 将参数传递给 forEach.call 中的函数

javascript - 如果值为 true,则通过 splice 删除数组项

javascript - TypeError : this. props.function 不是函数

javascript - 当一个 div 接触到滚动上的另一个 div 时返回的 jQuery 函数

javascript - 错误 : Failed to execute 'send' on 'XMLHttpRequest' : Failed to load 'file' : AngularJS SPA

c++ - 当我调用我的函数时,while 循环会跳过一个步骤

javascript - 返回 NaN 的数字?