views:

340

answers:

3

Hi
I'm trying to increment a value every second on the client side with jquery
this is what did:

<script type="text/javascript">
        $(document).ready(function increment(){
            $("#counter").text(parseInt($("#counter").text())+1);
            setTimeout(increment(),1000)
        })
    </script>

this is not working as expected and i get a "too much recursion" error.
any ideas on this?

+6  A: 

Try

$(document).ready(function () {       
    function increment(){
        $("#counter").text(parseInt($("#counter").text())+1);
        setTimeout(increment,1000);
    };            
    increment();
});

By the way, there is setInterval() to calling a function repeatedly at a set interval, rathering than recursively calling a function with setTimeout()

$(document).ready(function () {       
    var interval = setInterval(increment,1000);     
});

function increment(){
    $("#counter").text(parseInt($("#counter").text())+1);            
}
Russ Cam
+2  A: 

increment() is a call to increment, not a reference to it. When you're trying to set it up for increment to be called again, you're actually calling it again immediately. If it ever returned, its return value would be passed to setTimeout, but it never will because it simply calls itself again and again until you get a deep recursion error.

The solution is simply to remove the parentheses, so that you're referencing the function increment, and not calling it.

hobbs
+2  A: 

setTimeout(increment, 1000) should be the right syntax since you are passing a reference to a function.

Recursively calling setTimeout() without a stopping criteria is not recommended. The stack will blow eventually. Using setInterval() should be safe.

Joy Dutta