这里有一个办法,更符合JS设计(为那些谁还不知道函数式语言)的方式调整。而不是依靠一个全局变量,使用闭包:
$("#knap").click(function start()//named callback to bind && unbind:
{
$(this).unbind('click');//no need to start when started
$("#reset").unbind('click').click((function(timer)
{//timer is in scope thanks to closure
return function()
{//resets timer
clearInterval(timer);
timer = null;
$('#knap').click(start);//bind the start again
//alternatively, you could change the start button to a reset button on click and vice versa
}
})(setInterval((function(sec)
{
return function()
{
$('#timer').text(sec--);
if (sec === -1)
{
$('#reset').click();//stops interval
$('#reset').unbind('click');//no more need for the event
alert('done');
}//here's the interval counter: 15, passed as argument to closure
})(15),1000)));//set interval returns timer id, passed as argument to closure
});
现在,我承认这是相当混乱(和未经测试),但这种方式存在重置事件仅当它是必要的,你不使用任何全局变量。但最重要的,这就是JS的强大之处在于:作为第一类对象,将它们作为参数和返回值...只是去功能疯狂:)
我已经成立了一个工作Fiddle,太
-1丑陋的解决方案与全局变量... – Christoph 2012-08-02 15:51:54
我会接受你的答案。 – 2012-08-02 15:51:59
一流的代码。谢谢。 – Kavin 2014-11-15 17:38:25