Question

<script src = "http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
    $(document).ready(function(){
        $("#pad").mousedown(function(){
            $(this).css("background-color", "lightgrey");   
            var timer = 1;
            var up_timer = setInterval(function(){
                timer = timer + 1;
                $("#pad").html(timer);
            },1);
        }).mouseup(function(){

            $(this).css("background-color", "grey");
            clearInterval(up_timer);

        });
    });
</script>
<div style = "height:500px;width:600px;background-color:grey;border-radius:4px;margin:0 auto;margin-top:10%;" id = "pad"></div>
<input type = "button" id = "done" value = "done">

Hello, my code is very simple. There is a big grey box, that when you hold down on it, it goes lightgrey. And when you do hold down, a number appears in the box and increases very quickly. I want the number to STOP increasing on mouse up, but for some reason the number carries on increasing, but the colour of the box does go back to grey.

here it is on jsfiddle: http://jsfiddle.net/Bag47/1/

Thanks!

No correct solution

OTHER TIPS

up_timer was declared with var. It doesn't exist outside the function it was declared inside.

Remove the var from var up_timer = setInterval and declare it in a wider scope:

$(document).ready(function(){
    var up_timer;
    $("#pad").mousedown(function(){

JavaScript variables are scoped to the function in which they are defined, which means that up_timeris local to the function passed to mousedown and cannot be accessed outside of it.

Declaring the variable in the parent function makes it available throughout:

$(document).ready(function() {
    var up_timer;
    $("#pad").mousedown(function() {
        $(this).css("background-color", "lightgrey");   
        var timer = 1;
        up_timer = setInterval(function() {
            timer = timer + 1;
            $("#pad").html(timer);
        }, 1);
    }).mouseup(function() {
        $(this).css("background-color", "grey");
        clearInterval(up_timer);
    });
}); 

The up_time variable is not in scope in you mouseup handler. You needed to move it outwards in scope so it's still available in the mouseup handler.

New fiddle here http://jsfiddle.net/Bag47/2/

The important change is this, I've mode up_time upwards.

$(document).ready(function(){
    var up_timer;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top