我试图让一些对象与我的计时器一起工作。问题是,当我只有裸功能(不在对象中)时,它正在工作。但是当我把它放在对象里面时它不起作用。
使用此代码,我只看到00:01
当我只使用函数本身它工作正常时,我想将它们放在对象中我会在代码中有更多的函数。
感谢您的帮助
$(document).ready(function() {
var Timer = {
TimerID: null,
elapsed: 0,
changeTimer: function() {
this.TimerID = setInterval(this.timerTick(), 1000);
},
timerTick: function() {
this.elapsed++;
var minutes = Math.floor(this.elapsed / 60);
var seconds = this.elapsed - (minutes * 60);
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
$('.timer-html').text(minutes + ":" + seconds);
},
stopTimer: function() {
clearInterval(this.TimerID);
}
};
console.log(Timer);
$(".timer").click(Timer.changeTimer());
$(".stop-timer").click(Timer.stopTimer());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:;" class="timer">start clock</a>
<a href="javascript:;" class="stop-timer">stop clock</a>
<h1 class="timer-html">00:00</h1>
答案 0 :(得分:2)
$(document).ready(function() {
var Timer = {
TimerID : null,
elapsed : 0,
changeTimer: function () {
//here you need to send the delegate function without () //.. setInterval(this.timerTick
//this.TimerID = setInterval(this.timerTick.bind(this), 1000);
//arrow function variant
this.TimerID = setInterval(()=>this.timerTick(), 1000);
},
timerTick: function ()
{
this.elapsed++;
var elapsed = this.elapsed;
var minutes = Math.floor(elapsed / 60);
var seconds = elapsed - (minutes * 60);
if (minutes < 10)
minutes = "0" + minutes;
if (seconds < 10)
seconds = "0" + seconds;
$('.timer-html').text(minutes + ":" + seconds);
},
stopTimer: function () {
clearInterval(this.TimerID);
}
};
console.log(Timer);
//here you to keep the timer context, you can use arrow function
//.. ()=> or .bind(Timer)
$(".timer").click(()=> Timer.changeTimer());
$(".stop-timer").click(()=> Timer.stopTimer());
//.bind() variant
// $(".timer").click(Timer.changeTimer.bind(Timer));
// $(".stop-timer").click(Timer.stopTimer.bind(Timer));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<a href="javascript:;" class="timer">start clock</a>
<a href="javascript:;" class="stop-timer">stop clock</a>
<h1 class="timer-html">00:00</h1>
答案 1 :(得分:1)
将我的评论作为答案发布(当我相信它解决了这个问题时,将其留作评论有点愚蠢)。
setInterval(this.timerTick(), 1000);
似乎有误。
它正在执行timerTick
一次,然后将返回值undefined
传递给setInterval
。
而是直接传递timerTick
(不执行它)或将其包装在annon函数中。
:setInterval(() => this.timerTick(), 1000);
或setInterval(this.timerTick, 1000);
另请注意,setTimeout / setInterval将更改其执行的函数的上下文(this
)。 annon方法将防止这种情况发生。但是,您也可以在将函数传递给setInterval之前绑定该函数。