封装在对象中的JavaScript Timer无法正常运行,请求帮助
解决计时器对象封装后的失效问题
我来帮你搞定这个计时器的问题!你的代码里有几个关键的小问题导致封装后失效,咱们一步步理清楚并修复:
核心错误点分析
- 点击事件绑定错误:你直接调用了
Timer.changeTimer()和Timer.stopTimer(),这会导致页面加载时就执行这些函数,而不是点击按钮时触发。同时选择器写错了,应该用class选择器(.timer和.stop-timer),而不是标签选择器。 setInterval的this指向问题:setInterval(this.timerTick(), 1000)里的this.timerTick()是立即执行函数,而且即使去掉括号,回调执行时this会指向window,而非Timer对象,导致无法正确更新elapsed属性。- 回调函数的上下文丢失:定时器回调默认的
this不是你的Timer对象,需要手动绑定上下文来保证访问到对象内的属性和方法。
修正后的完整代码
$(document).ready(function() { var Timer = { TimerID: null, elapsed: 0, changeTimer: function() { // 用bind绑定this,保证timerTick里的this指向Timer对象 this.TimerID = setInterval(this.timerTick.bind(this), 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); } }; // 绑定点击事件时传函数引用,不要加括号;同时修正选择器 $(".timer").click(function() { Timer.changeTimer(); }); $(".stop-timer").click(function() { 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>
关键修改说明
- 点击事件绑定:把
$("timer").click(Timer.changeTimer())改成$(".timer").click(function() { Timer.changeTimer(); }),这样点击时才会调用changeTimer,同时修正了class选择器的写法。 - 定时器回调的上下文绑定:用
this.timerTick.bind(this)代替this.timerTick(),既避免了立即执行函数,又把timerTick的this绑定到当前的Timer对象,确保能正确访问this.elapsed和修改DOM。 - 停止按钮的绑定同理:修正选择器并传递函数引用,确保点击停止按钮时才执行
stopTimer。
这样修改后,你的计时器就能正常工作了,而且保留了对象的形式,方便后续扩展更多功能(比如重置计时器、暂停后继续计时等)。
内容的提问来源于stack exchange,提问作者DeiForm
相关产品推荐
相关产品推荐

