Yaniv Golan Yaniv Golan - 5 months ago 21
Javascript Question

setTimeout recursion with Jquery

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?

Answer

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