Question

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?

Was it helpful?

Solution

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);            
}  

OTHER TIPS

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.

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.

A simpler way: "A function which is called as soon as created and repeats inside 1000 ms intervals if 'something' is not true"

(function(){
    if (something) {
        doSomething();
    } else {
        setTimeout(arguments.callee, 1000);
    }
})();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top