Here's an approach that more closely matches how JS was designed (as a functional language for those who don't know yet). Instead of relying on a global variable, use closure:
$("#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 the interval counter: 15, passed as argument to closure })(15),1000)));//set interval returns timer id, passed as argument to closure });
Now I admit that this is pretty messy (and unchecked), but that way there the reset event is only available when it is needed, and you are not using any global variables. But to a decisive extent, this is where the power of JS is located: it functions as first-class objects, passing them as arguments and return values ... just go to the crazy function :)
I also created a working feed
Elias van ootegem
source share