作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我该如何将这整个事情变成一个创建新的可控计时器的函数?
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/
我只是在测试一些基本的 html 和 css 东西,当我遇到一个我根本无法解决的问题时。 文件: test2.html: Abschitt 1
我是一名优秀的程序员,十分优秀!