2
<script>
$(document).ready(function(){
    $('body').keyup(function(e){
       if(e.keyCode == 32){

        if(foo == 1)
        {
            clearInterval(myinterval);
            foo = 0;
        } else {

        $('#h2').text('STOPPA MED SPACE!');
        var start       = new Date;
        var foo;
        var myinterval  = setInterval(function() {$('.Timer').text((new Date - start) / 1000); }, 10);

        foo = 1;

        }

       }
    });
});
</script>

Above is my jQuery code. When I press the space button on my keyboard I start a timer which count up. How can I stop this timer if I press space again? I can always add a var foo = 0; which tells if the interval is ongoing or not. But how can I stop this interval?

user3218338
  • 652
  • 1
  • 8
  • 20

1 Answers1

4

Try this

var yourInterval = setInterval(function() {....},10);

clearInterval(yourInterval);

See the docs for setInterval() and clearInterval().

Pesulap
  • 884
  • 8
  • 19