Why does the setInterval callback execute only once?












61















I have this counter I made but I want it to run forever, it's really simple, what am I doing wrong here?



function timer() {
console.log("timer!")
}

window.setInterval(timer(), 1000)









share|improve this question




















  • 7





    The problem is timer() invokes the function-object that resulted from evaluating timer and then passes the result (undefined) to setTimeout. So, don't invoke it. Instead, just pass the function-object: setInterval(timer, 1000)

    – user166390
    Apr 16 '12 at 22:57


















61















I have this counter I made but I want it to run forever, it's really simple, what am I doing wrong here?



function timer() {
console.log("timer!")
}

window.setInterval(timer(), 1000)









share|improve this question




















  • 7





    The problem is timer() invokes the function-object that resulted from evaluating timer and then passes the result (undefined) to setTimeout. So, don't invoke it. Instead, just pass the function-object: setInterval(timer, 1000)

    – user166390
    Apr 16 '12 at 22:57
















61












61








61


11






I have this counter I made but I want it to run forever, it's really simple, what am I doing wrong here?



function timer() {
console.log("timer!")
}

window.setInterval(timer(), 1000)









share|improve this question
















I have this counter I made but I want it to run forever, it's really simple, what am I doing wrong here?



function timer() {
console.log("timer!")
}

window.setInterval(timer(), 1000)






javascript callback setinterval






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 9 '18 at 11:52









Ivar

2,871113140




2,871113140










asked Apr 16 '12 at 22:39









computer_smilecomputer_smile

72011534




72011534








  • 7





    The problem is timer() invokes the function-object that resulted from evaluating timer and then passes the result (undefined) to setTimeout. So, don't invoke it. Instead, just pass the function-object: setInterval(timer, 1000)

    – user166390
    Apr 16 '12 at 22:57
















  • 7





    The problem is timer() invokes the function-object that resulted from evaluating timer and then passes the result (undefined) to setTimeout. So, don't invoke it. Instead, just pass the function-object: setInterval(timer, 1000)

    – user166390
    Apr 16 '12 at 22:57










7




7





The problem is timer() invokes the function-object that resulted from evaluating timer and then passes the result (undefined) to setTimeout. So, don't invoke it. Instead, just pass the function-object: setInterval(timer, 1000)

– user166390
Apr 16 '12 at 22:57







The problem is timer() invokes the function-object that resulted from evaluating timer and then passes the result (undefined) to setTimeout. So, don't invoke it. Instead, just pass the function-object: setInterval(timer, 1000)

– user166390
Apr 16 '12 at 22:57














2 Answers
2






active

oldest

votes


















96














You used a function call instead of a function reference as the first parameter of the setInterval. Do it like this:



function timer() {
console.log("timer!");
}

window.setInterval(timer, 1000);


Or shorter (but when the function gets bigger also less readable):



window.setInterval( function() {
console.log("timer!");
}, 1000)





share|improve this answer





















  • 2





    the answer correctly points out that the callback function should not have the "()" in the argument.

    – Kristian
    Apr 16 '12 at 22:42








  • 2





    According to developer.mozilla.org/en/Extensions/…, the shorter version may cause memory leak.

    – Crend King
    Apr 16 '12 at 22:46






  • 2





    @CrendKing Both versions have the exact same "issue" (also, that is for extensions and does not affect normal webpages/JS) as it is object lifetime that matters.

    – user166390
    Apr 16 '12 at 23:14













  • That's why I said "may", since OP does not specify his use case. Just pay attention if it is extracted from an Mozilla extension.

    – Crend King
    Apr 16 '12 at 23:32













  • How can we change the interval value, for e.g. I have array[10, 5, 2] and want to call timer() based on the interval defined in array. Thanks!

    – OverrockSTAR
    Mar 9 '17 at 15:46



















9














setInterval and setTimeout must be used with callbacks, like:



setInterval(timer, 1000);


or unnamed functions:



setInterval( function() { console.log("timer!"); }, 1000 );


Why your code is not working - when you pass a function as argument to another function with brackets e.g. doSomething ( someFunc() ) you are passing the result of the function.



When the function is passed as object e.g. doSomething ( someFunc ) you are passing a callback. This way someFunc is passed as reference and it is executed somewhere in the calling function. This is the same as the pointers to functions in other languages.



A common mistake is to use the these two functions as shown at w3schools. This makes an implicit call to eval.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10182714%2fwhy-does-the-setinterval-callback-execute-only-once%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    96














    You used a function call instead of a function reference as the first parameter of the setInterval. Do it like this:



    function timer() {
    console.log("timer!");
    }

    window.setInterval(timer, 1000);


    Or shorter (but when the function gets bigger also less readable):



    window.setInterval( function() {
    console.log("timer!");
    }, 1000)





    share|improve this answer





















    • 2





      the answer correctly points out that the callback function should not have the "()" in the argument.

      – Kristian
      Apr 16 '12 at 22:42








    • 2





      According to developer.mozilla.org/en/Extensions/…, the shorter version may cause memory leak.

      – Crend King
      Apr 16 '12 at 22:46






    • 2





      @CrendKing Both versions have the exact same "issue" (also, that is for extensions and does not affect normal webpages/JS) as it is object lifetime that matters.

      – user166390
      Apr 16 '12 at 23:14













    • That's why I said "may", since OP does not specify his use case. Just pay attention if it is extracted from an Mozilla extension.

      – Crend King
      Apr 16 '12 at 23:32













    • How can we change the interval value, for e.g. I have array[10, 5, 2] and want to call timer() based on the interval defined in array. Thanks!

      – OverrockSTAR
      Mar 9 '17 at 15:46
















    96














    You used a function call instead of a function reference as the first parameter of the setInterval. Do it like this:



    function timer() {
    console.log("timer!");
    }

    window.setInterval(timer, 1000);


    Or shorter (but when the function gets bigger also less readable):



    window.setInterval( function() {
    console.log("timer!");
    }, 1000)





    share|improve this answer





















    • 2





      the answer correctly points out that the callback function should not have the "()" in the argument.

      – Kristian
      Apr 16 '12 at 22:42








    • 2





      According to developer.mozilla.org/en/Extensions/…, the shorter version may cause memory leak.

      – Crend King
      Apr 16 '12 at 22:46






    • 2





      @CrendKing Both versions have the exact same "issue" (also, that is for extensions and does not affect normal webpages/JS) as it is object lifetime that matters.

      – user166390
      Apr 16 '12 at 23:14













    • That's why I said "may", since OP does not specify his use case. Just pay attention if it is extracted from an Mozilla extension.

      – Crend King
      Apr 16 '12 at 23:32













    • How can we change the interval value, for e.g. I have array[10, 5, 2] and want to call timer() based on the interval defined in array. Thanks!

      – OverrockSTAR
      Mar 9 '17 at 15:46














    96












    96








    96







    You used a function call instead of a function reference as the first parameter of the setInterval. Do it like this:



    function timer() {
    console.log("timer!");
    }

    window.setInterval(timer, 1000);


    Or shorter (but when the function gets bigger also less readable):



    window.setInterval( function() {
    console.log("timer!");
    }, 1000)





    share|improve this answer















    You used a function call instead of a function reference as the first parameter of the setInterval. Do it like this:



    function timer() {
    console.log("timer!");
    }

    window.setInterval(timer, 1000);


    Or shorter (but when the function gets bigger also less readable):



    window.setInterval( function() {
    console.log("timer!");
    }, 1000)






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Apr 16 '12 at 23:17

























    answered Apr 16 '12 at 22:40









    Koen PetersKoen Peters

    11k52949




    11k52949








    • 2





      the answer correctly points out that the callback function should not have the "()" in the argument.

      – Kristian
      Apr 16 '12 at 22:42








    • 2





      According to developer.mozilla.org/en/Extensions/…, the shorter version may cause memory leak.

      – Crend King
      Apr 16 '12 at 22:46






    • 2





      @CrendKing Both versions have the exact same "issue" (also, that is for extensions and does not affect normal webpages/JS) as it is object lifetime that matters.

      – user166390
      Apr 16 '12 at 23:14













    • That's why I said "may", since OP does not specify his use case. Just pay attention if it is extracted from an Mozilla extension.

      – Crend King
      Apr 16 '12 at 23:32













    • How can we change the interval value, for e.g. I have array[10, 5, 2] and want to call timer() based on the interval defined in array. Thanks!

      – OverrockSTAR
      Mar 9 '17 at 15:46














    • 2





      the answer correctly points out that the callback function should not have the "()" in the argument.

      – Kristian
      Apr 16 '12 at 22:42








    • 2





      According to developer.mozilla.org/en/Extensions/…, the shorter version may cause memory leak.

      – Crend King
      Apr 16 '12 at 22:46






    • 2





      @CrendKing Both versions have the exact same "issue" (also, that is for extensions and does not affect normal webpages/JS) as it is object lifetime that matters.

      – user166390
      Apr 16 '12 at 23:14













    • That's why I said "may", since OP does not specify his use case. Just pay attention if it is extracted from an Mozilla extension.

      – Crend King
      Apr 16 '12 at 23:32













    • How can we change the interval value, for e.g. I have array[10, 5, 2] and want to call timer() based on the interval defined in array. Thanks!

      – OverrockSTAR
      Mar 9 '17 at 15:46








    2




    2





    the answer correctly points out that the callback function should not have the "()" in the argument.

    – Kristian
    Apr 16 '12 at 22:42







    the answer correctly points out that the callback function should not have the "()" in the argument.

    – Kristian
    Apr 16 '12 at 22:42






    2




    2





    According to developer.mozilla.org/en/Extensions/…, the shorter version may cause memory leak.

    – Crend King
    Apr 16 '12 at 22:46





    According to developer.mozilla.org/en/Extensions/…, the shorter version may cause memory leak.

    – Crend King
    Apr 16 '12 at 22:46




    2




    2





    @CrendKing Both versions have the exact same "issue" (also, that is for extensions and does not affect normal webpages/JS) as it is object lifetime that matters.

    – user166390
    Apr 16 '12 at 23:14







    @CrendKing Both versions have the exact same "issue" (also, that is for extensions and does not affect normal webpages/JS) as it is object lifetime that matters.

    – user166390
    Apr 16 '12 at 23:14















    That's why I said "may", since OP does not specify his use case. Just pay attention if it is extracted from an Mozilla extension.

    – Crend King
    Apr 16 '12 at 23:32







    That's why I said "may", since OP does not specify his use case. Just pay attention if it is extracted from an Mozilla extension.

    – Crend King
    Apr 16 '12 at 23:32















    How can we change the interval value, for e.g. I have array[10, 5, 2] and want to call timer() based on the interval defined in array. Thanks!

    – OverrockSTAR
    Mar 9 '17 at 15:46





    How can we change the interval value, for e.g. I have array[10, 5, 2] and want to call timer() based on the interval defined in array. Thanks!

    – OverrockSTAR
    Mar 9 '17 at 15:46













    9














    setInterval and setTimeout must be used with callbacks, like:



    setInterval(timer, 1000);


    or unnamed functions:



    setInterval( function() { console.log("timer!"); }, 1000 );


    Why your code is not working - when you pass a function as argument to another function with brackets e.g. doSomething ( someFunc() ) you are passing the result of the function.



    When the function is passed as object e.g. doSomething ( someFunc ) you are passing a callback. This way someFunc is passed as reference and it is executed somewhere in the calling function. This is the same as the pointers to functions in other languages.



    A common mistake is to use the these two functions as shown at w3schools. This makes an implicit call to eval.






    share|improve this answer




























      9














      setInterval and setTimeout must be used with callbacks, like:



      setInterval(timer, 1000);


      or unnamed functions:



      setInterval( function() { console.log("timer!"); }, 1000 );


      Why your code is not working - when you pass a function as argument to another function with brackets e.g. doSomething ( someFunc() ) you are passing the result of the function.



      When the function is passed as object e.g. doSomething ( someFunc ) you are passing a callback. This way someFunc is passed as reference and it is executed somewhere in the calling function. This is the same as the pointers to functions in other languages.



      A common mistake is to use the these two functions as shown at w3schools. This makes an implicit call to eval.






      share|improve this answer


























        9












        9








        9







        setInterval and setTimeout must be used with callbacks, like:



        setInterval(timer, 1000);


        or unnamed functions:



        setInterval( function() { console.log("timer!"); }, 1000 );


        Why your code is not working - when you pass a function as argument to another function with brackets e.g. doSomething ( someFunc() ) you are passing the result of the function.



        When the function is passed as object e.g. doSomething ( someFunc ) you are passing a callback. This way someFunc is passed as reference and it is executed somewhere in the calling function. This is the same as the pointers to functions in other languages.



        A common mistake is to use the these two functions as shown at w3schools. This makes an implicit call to eval.






        share|improve this answer













        setInterval and setTimeout must be used with callbacks, like:



        setInterval(timer, 1000);


        or unnamed functions:



        setInterval( function() { console.log("timer!"); }, 1000 );


        Why your code is not working - when you pass a function as argument to another function with brackets e.g. doSomething ( someFunc() ) you are passing the result of the function.



        When the function is passed as object e.g. doSomething ( someFunc ) you are passing a callback. This way someFunc is passed as reference and it is executed somewhere in the calling function. This is the same as the pointers to functions in other languages.



        A common mistake is to use the these two functions as shown at w3schools. This makes an implicit call to eval.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Apr 17 '12 at 12:52









        BakudanBakudan

        13.7k84265




        13.7k84265






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10182714%2fwhy-does-the-setinterval-callback-execute-only-once%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to send String Array data to Server using php in android

            Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

            Is anime1.com a legal site for watching anime?