Decreasing a variable by increments over time with setInterval












0















So right now, I am a beginner in coding and I'm having quite a few issues with the setInterval command. What I am trying to do is have a function that decreases a variable by 1 every time 5 seconds pass. However, although I have looked at many different threads with information about the setInterval command, none of them seem to fit my needs (although I may have missed something) and I have been unable to manipulate anything I have seen elsewhere to perform my function.



while (fullness <= 10) {
setInterval(hungry{ fullness--; }, 1000);
}









share|improve this question


















  • 1





    Welcome to Stack Overflow. Let's see if you can provide some more information. What are you intending to do? What is hungry? Are you intending that to be a function call? Do you understand the difference between setTimeout and setInterval, to see which is more appropriate here?

    – wlh
    Nov 20 '18 at 18:08











  • Right now, I am trying to have a function that decreases the variable "fullness" by 1 every few seconds, and hungry is supposed to be the function that is "fullness--".

    – Cake_Commander
    Nov 21 '18 at 3:12
















0















So right now, I am a beginner in coding and I'm having quite a few issues with the setInterval command. What I am trying to do is have a function that decreases a variable by 1 every time 5 seconds pass. However, although I have looked at many different threads with information about the setInterval command, none of them seem to fit my needs (although I may have missed something) and I have been unable to manipulate anything I have seen elsewhere to perform my function.



while (fullness <= 10) {
setInterval(hungry{ fullness--; }, 1000);
}









share|improve this question


















  • 1





    Welcome to Stack Overflow. Let's see if you can provide some more information. What are you intending to do? What is hungry? Are you intending that to be a function call? Do you understand the difference between setTimeout and setInterval, to see which is more appropriate here?

    – wlh
    Nov 20 '18 at 18:08











  • Right now, I am trying to have a function that decreases the variable "fullness" by 1 every few seconds, and hungry is supposed to be the function that is "fullness--".

    – Cake_Commander
    Nov 21 '18 at 3:12














0












0








0








So right now, I am a beginner in coding and I'm having quite a few issues with the setInterval command. What I am trying to do is have a function that decreases a variable by 1 every time 5 seconds pass. However, although I have looked at many different threads with information about the setInterval command, none of them seem to fit my needs (although I may have missed something) and I have been unable to manipulate anything I have seen elsewhere to perform my function.



while (fullness <= 10) {
setInterval(hungry{ fullness--; }, 1000);
}









share|improve this question














So right now, I am a beginner in coding and I'm having quite a few issues with the setInterval command. What I am trying to do is have a function that decreases a variable by 1 every time 5 seconds pass. However, although I have looked at many different threads with information about the setInterval command, none of them seem to fit my needs (although I may have missed something) and I have been unable to manipulate anything I have seen elsewhere to perform my function.



while (fullness <= 10) {
setInterval(hungry{ fullness--; }, 1000);
}






javascript html






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 '18 at 18:01









Cake_CommanderCake_Commander

42




42








  • 1





    Welcome to Stack Overflow. Let's see if you can provide some more information. What are you intending to do? What is hungry? Are you intending that to be a function call? Do you understand the difference between setTimeout and setInterval, to see which is more appropriate here?

    – wlh
    Nov 20 '18 at 18:08











  • Right now, I am trying to have a function that decreases the variable "fullness" by 1 every few seconds, and hungry is supposed to be the function that is "fullness--".

    – Cake_Commander
    Nov 21 '18 at 3:12














  • 1





    Welcome to Stack Overflow. Let's see if you can provide some more information. What are you intending to do? What is hungry? Are you intending that to be a function call? Do you understand the difference between setTimeout and setInterval, to see which is more appropriate here?

    – wlh
    Nov 20 '18 at 18:08











  • Right now, I am trying to have a function that decreases the variable "fullness" by 1 every few seconds, and hungry is supposed to be the function that is "fullness--".

    – Cake_Commander
    Nov 21 '18 at 3:12








1




1





Welcome to Stack Overflow. Let's see if you can provide some more information. What are you intending to do? What is hungry? Are you intending that to be a function call? Do you understand the difference between setTimeout and setInterval, to see which is more appropriate here?

– wlh
Nov 20 '18 at 18:08





Welcome to Stack Overflow. Let's see if you can provide some more information. What are you intending to do? What is hungry? Are you intending that to be a function call? Do you understand the difference between setTimeout and setInterval, to see which is more appropriate here?

– wlh
Nov 20 '18 at 18:08













Right now, I am trying to have a function that decreases the variable "fullness" by 1 every few seconds, and hungry is supposed to be the function that is "fullness--".

– Cake_Commander
Nov 21 '18 at 3:12





Right now, I am trying to have a function that decreases the variable "fullness" by 1 every few seconds, and hungry is supposed to be the function that is "fullness--".

– Cake_Commander
Nov 21 '18 at 3:12












4 Answers
4






active

oldest

votes


















1














Why your code is wrong:



//There is no need to loop and call setInterval multiple times
//setInterval will fire the callback function every x milliseconds,
//In your example you have it firing every 1 second(1000 milliseconds)
//while (fullness <= 10) {
//setInterval(hungry{ fullness--; }, 1000);
//}


To fix this:
On page load (document.ready in jquery)
Do just one call to setInterval()



setInterval(function(){
if(fullness <= 10){
hungry{ fullness--; }; //Not sure about this line as it comes from your example
}
}, 5000); //Pass second parameter to setInterval of 5000 milliseconds (5 seconds wait)





share|improve this answer
























  • The "hungry{ fullness--; };" was supposed to imitate the "(function(){ alert("Hello");" part of the code, but I was kinf of confused by that.

    – Cake_Commander
    Nov 21 '18 at 17:59











  • @Cake_Commander If you just need to reduce fullness by one, you can remove the hungry{} and replace it with fullness-- in my example.

    – Ryan Wilson
    Nov 21 '18 at 18:00











  • Alright, I think I mostly get it now. Should I replace the "function()" with the desired function name like this? setInterval(HUNGER(){ if(fullness <= 10){ fullness--; } }, 5000);

    – Cake_Commander
    Nov 21 '18 at 18:47











  • @Cake_Commander if you want to replace the function() with your own function name then you just use the name, like setInterval(HUNGER, 5000); And then in the function HUNGER() { if(fullness <= 10) { fullness--; } }

    – Ryan Wilson
    Nov 21 '18 at 18:53











  • I understand now, thank you for your help!

    – Cake_Commander
    Nov 22 '18 at 23:36



















0














You may be trying to use setInterval() in a synchronous way rather than asynchronously.



When you call setInterval(function, period) it only begins a timer that calls the given function every period milliseconds. After calling setInterval javascript will continue to execute the next lines of code right away. If you were to check for your fullness value right after the while loop ends, you might notice it hasn't changed (yet!).



I suggest that you write a new function to handle changing fullness and reacting to the change:



function updateHunger() {
fullness--;
if (fullness < 10) {
//Do something
}
else {
//You have to call clearInterval() to stop the timer
clearInterval(hungerTimer);
}
}


Then use setInterval like this:



//Using a variable to store the timer reference that we create
hungerTimer = setInterval(updateHunger, 5000);


Remember to declare the hungerTimer variable in a scope where it can be accessed from both updateHunger() and the method that calls setInterval().






share|improve this answer































    0














    You have to first set a variable for setInterval and then stop the iteration with clearInterval (important, otherwise the loop will iterate indefinitely). And check for fullness to be greater than 0.



    var fullness = 10;
    var timer = setInterval(function(){
    if(fullness > 0){
    fullness--;
    }
    else{
    clearInterval(timer);
    }
    }, 5000);


    Here is the working jsFiddle






    share|improve this answer

































      0














      The reason you are bumping into this is that JS runs in a single thread. Blocking it by waiting for 1 second would make the entire browser stall, which is why JS does not allow it and we do not have sleep() in JS, we have the Timers API.



      But it's nonetheless nice to write straight up for-loops that look synchronous because that's how we "normally" think. That's why you can actually nowadays write something like this if using an engine with async and generator support:



      // ES6 features

      const sleeper = (x, timeout) =>
      new Promise(resolve => setTimeout(resolve, timeout, x));

      function* timer(count, timeout) {
      for (let i = count; i >= 0; i--) {
      yield sleeper(i, timeout);
      }
      }

      async function main() {
      for (let i of timer(10, 1000)) {
      console.log(await i); // Blocks the main() function but not the JS main thread!
      }
      }

      main();
      console.log("The call to main() was non-blocking");





      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%2f53398909%2fdecreasing-a-variable-by-increments-over-time-with-setinterval%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        Why your code is wrong:



        //There is no need to loop and call setInterval multiple times
        //setInterval will fire the callback function every x milliseconds,
        //In your example you have it firing every 1 second(1000 milliseconds)
        //while (fullness <= 10) {
        //setInterval(hungry{ fullness--; }, 1000);
        //}


        To fix this:
        On page load (document.ready in jquery)
        Do just one call to setInterval()



        setInterval(function(){
        if(fullness <= 10){
        hungry{ fullness--; }; //Not sure about this line as it comes from your example
        }
        }, 5000); //Pass second parameter to setInterval of 5000 milliseconds (5 seconds wait)





        share|improve this answer
























        • The "hungry{ fullness--; };" was supposed to imitate the "(function(){ alert("Hello");" part of the code, but I was kinf of confused by that.

          – Cake_Commander
          Nov 21 '18 at 17:59











        • @Cake_Commander If you just need to reduce fullness by one, you can remove the hungry{} and replace it with fullness-- in my example.

          – Ryan Wilson
          Nov 21 '18 at 18:00











        • Alright, I think I mostly get it now. Should I replace the "function()" with the desired function name like this? setInterval(HUNGER(){ if(fullness <= 10){ fullness--; } }, 5000);

          – Cake_Commander
          Nov 21 '18 at 18:47











        • @Cake_Commander if you want to replace the function() with your own function name then you just use the name, like setInterval(HUNGER, 5000); And then in the function HUNGER() { if(fullness <= 10) { fullness--; } }

          – Ryan Wilson
          Nov 21 '18 at 18:53











        • I understand now, thank you for your help!

          – Cake_Commander
          Nov 22 '18 at 23:36
















        1














        Why your code is wrong:



        //There is no need to loop and call setInterval multiple times
        //setInterval will fire the callback function every x milliseconds,
        //In your example you have it firing every 1 second(1000 milliseconds)
        //while (fullness <= 10) {
        //setInterval(hungry{ fullness--; }, 1000);
        //}


        To fix this:
        On page load (document.ready in jquery)
        Do just one call to setInterval()



        setInterval(function(){
        if(fullness <= 10){
        hungry{ fullness--; }; //Not sure about this line as it comes from your example
        }
        }, 5000); //Pass second parameter to setInterval of 5000 milliseconds (5 seconds wait)





        share|improve this answer
























        • The "hungry{ fullness--; };" was supposed to imitate the "(function(){ alert("Hello");" part of the code, but I was kinf of confused by that.

          – Cake_Commander
          Nov 21 '18 at 17:59











        • @Cake_Commander If you just need to reduce fullness by one, you can remove the hungry{} and replace it with fullness-- in my example.

          – Ryan Wilson
          Nov 21 '18 at 18:00











        • Alright, I think I mostly get it now. Should I replace the "function()" with the desired function name like this? setInterval(HUNGER(){ if(fullness <= 10){ fullness--; } }, 5000);

          – Cake_Commander
          Nov 21 '18 at 18:47











        • @Cake_Commander if you want to replace the function() with your own function name then you just use the name, like setInterval(HUNGER, 5000); And then in the function HUNGER() { if(fullness <= 10) { fullness--; } }

          – Ryan Wilson
          Nov 21 '18 at 18:53











        • I understand now, thank you for your help!

          – Cake_Commander
          Nov 22 '18 at 23:36














        1












        1








        1







        Why your code is wrong:



        //There is no need to loop and call setInterval multiple times
        //setInterval will fire the callback function every x milliseconds,
        //In your example you have it firing every 1 second(1000 milliseconds)
        //while (fullness <= 10) {
        //setInterval(hungry{ fullness--; }, 1000);
        //}


        To fix this:
        On page load (document.ready in jquery)
        Do just one call to setInterval()



        setInterval(function(){
        if(fullness <= 10){
        hungry{ fullness--; }; //Not sure about this line as it comes from your example
        }
        }, 5000); //Pass second parameter to setInterval of 5000 milliseconds (5 seconds wait)





        share|improve this answer













        Why your code is wrong:



        //There is no need to loop and call setInterval multiple times
        //setInterval will fire the callback function every x milliseconds,
        //In your example you have it firing every 1 second(1000 milliseconds)
        //while (fullness <= 10) {
        //setInterval(hungry{ fullness--; }, 1000);
        //}


        To fix this:
        On page load (document.ready in jquery)
        Do just one call to setInterval()



        setInterval(function(){
        if(fullness <= 10){
        hungry{ fullness--; }; //Not sure about this line as it comes from your example
        }
        }, 5000); //Pass second parameter to setInterval of 5000 milliseconds (5 seconds wait)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 '18 at 18:07









        Ryan WilsonRyan Wilson

        3,9941619




        3,9941619













        • The "hungry{ fullness--; };" was supposed to imitate the "(function(){ alert("Hello");" part of the code, but I was kinf of confused by that.

          – Cake_Commander
          Nov 21 '18 at 17:59











        • @Cake_Commander If you just need to reduce fullness by one, you can remove the hungry{} and replace it with fullness-- in my example.

          – Ryan Wilson
          Nov 21 '18 at 18:00











        • Alright, I think I mostly get it now. Should I replace the "function()" with the desired function name like this? setInterval(HUNGER(){ if(fullness <= 10){ fullness--; } }, 5000);

          – Cake_Commander
          Nov 21 '18 at 18:47











        • @Cake_Commander if you want to replace the function() with your own function name then you just use the name, like setInterval(HUNGER, 5000); And then in the function HUNGER() { if(fullness <= 10) { fullness--; } }

          – Ryan Wilson
          Nov 21 '18 at 18:53











        • I understand now, thank you for your help!

          – Cake_Commander
          Nov 22 '18 at 23:36



















        • The "hungry{ fullness--; };" was supposed to imitate the "(function(){ alert("Hello");" part of the code, but I was kinf of confused by that.

          – Cake_Commander
          Nov 21 '18 at 17:59











        • @Cake_Commander If you just need to reduce fullness by one, you can remove the hungry{} and replace it with fullness-- in my example.

          – Ryan Wilson
          Nov 21 '18 at 18:00











        • Alright, I think I mostly get it now. Should I replace the "function()" with the desired function name like this? setInterval(HUNGER(){ if(fullness <= 10){ fullness--; } }, 5000);

          – Cake_Commander
          Nov 21 '18 at 18:47











        • @Cake_Commander if you want to replace the function() with your own function name then you just use the name, like setInterval(HUNGER, 5000); And then in the function HUNGER() { if(fullness <= 10) { fullness--; } }

          – Ryan Wilson
          Nov 21 '18 at 18:53











        • I understand now, thank you for your help!

          – Cake_Commander
          Nov 22 '18 at 23:36

















        The "hungry{ fullness--; };" was supposed to imitate the "(function(){ alert("Hello");" part of the code, but I was kinf of confused by that.

        – Cake_Commander
        Nov 21 '18 at 17:59





        The "hungry{ fullness--; };" was supposed to imitate the "(function(){ alert("Hello");" part of the code, but I was kinf of confused by that.

        – Cake_Commander
        Nov 21 '18 at 17:59













        @Cake_Commander If you just need to reduce fullness by one, you can remove the hungry{} and replace it with fullness-- in my example.

        – Ryan Wilson
        Nov 21 '18 at 18:00





        @Cake_Commander If you just need to reduce fullness by one, you can remove the hungry{} and replace it with fullness-- in my example.

        – Ryan Wilson
        Nov 21 '18 at 18:00













        Alright, I think I mostly get it now. Should I replace the "function()" with the desired function name like this? setInterval(HUNGER(){ if(fullness <= 10){ fullness--; } }, 5000);

        – Cake_Commander
        Nov 21 '18 at 18:47





        Alright, I think I mostly get it now. Should I replace the "function()" with the desired function name like this? setInterval(HUNGER(){ if(fullness <= 10){ fullness--; } }, 5000);

        – Cake_Commander
        Nov 21 '18 at 18:47













        @Cake_Commander if you want to replace the function() with your own function name then you just use the name, like setInterval(HUNGER, 5000); And then in the function HUNGER() { if(fullness <= 10) { fullness--; } }

        – Ryan Wilson
        Nov 21 '18 at 18:53





        @Cake_Commander if you want to replace the function() with your own function name then you just use the name, like setInterval(HUNGER, 5000); And then in the function HUNGER() { if(fullness <= 10) { fullness--; } }

        – Ryan Wilson
        Nov 21 '18 at 18:53













        I understand now, thank you for your help!

        – Cake_Commander
        Nov 22 '18 at 23:36





        I understand now, thank you for your help!

        – Cake_Commander
        Nov 22 '18 at 23:36













        0














        You may be trying to use setInterval() in a synchronous way rather than asynchronously.



        When you call setInterval(function, period) it only begins a timer that calls the given function every period milliseconds. After calling setInterval javascript will continue to execute the next lines of code right away. If you were to check for your fullness value right after the while loop ends, you might notice it hasn't changed (yet!).



        I suggest that you write a new function to handle changing fullness and reacting to the change:



        function updateHunger() {
        fullness--;
        if (fullness < 10) {
        //Do something
        }
        else {
        //You have to call clearInterval() to stop the timer
        clearInterval(hungerTimer);
        }
        }


        Then use setInterval like this:



        //Using a variable to store the timer reference that we create
        hungerTimer = setInterval(updateHunger, 5000);


        Remember to declare the hungerTimer variable in a scope where it can be accessed from both updateHunger() and the method that calls setInterval().






        share|improve this answer




























          0














          You may be trying to use setInterval() in a synchronous way rather than asynchronously.



          When you call setInterval(function, period) it only begins a timer that calls the given function every period milliseconds. After calling setInterval javascript will continue to execute the next lines of code right away. If you were to check for your fullness value right after the while loop ends, you might notice it hasn't changed (yet!).



          I suggest that you write a new function to handle changing fullness and reacting to the change:



          function updateHunger() {
          fullness--;
          if (fullness < 10) {
          //Do something
          }
          else {
          //You have to call clearInterval() to stop the timer
          clearInterval(hungerTimer);
          }
          }


          Then use setInterval like this:



          //Using a variable to store the timer reference that we create
          hungerTimer = setInterval(updateHunger, 5000);


          Remember to declare the hungerTimer variable in a scope where it can be accessed from both updateHunger() and the method that calls setInterval().






          share|improve this answer


























            0












            0








            0







            You may be trying to use setInterval() in a synchronous way rather than asynchronously.



            When you call setInterval(function, period) it only begins a timer that calls the given function every period milliseconds. After calling setInterval javascript will continue to execute the next lines of code right away. If you were to check for your fullness value right after the while loop ends, you might notice it hasn't changed (yet!).



            I suggest that you write a new function to handle changing fullness and reacting to the change:



            function updateHunger() {
            fullness--;
            if (fullness < 10) {
            //Do something
            }
            else {
            //You have to call clearInterval() to stop the timer
            clearInterval(hungerTimer);
            }
            }


            Then use setInterval like this:



            //Using a variable to store the timer reference that we create
            hungerTimer = setInterval(updateHunger, 5000);


            Remember to declare the hungerTimer variable in a scope where it can be accessed from both updateHunger() and the method that calls setInterval().






            share|improve this answer













            You may be trying to use setInterval() in a synchronous way rather than asynchronously.



            When you call setInterval(function, period) it only begins a timer that calls the given function every period milliseconds. After calling setInterval javascript will continue to execute the next lines of code right away. If you were to check for your fullness value right after the while loop ends, you might notice it hasn't changed (yet!).



            I suggest that you write a new function to handle changing fullness and reacting to the change:



            function updateHunger() {
            fullness--;
            if (fullness < 10) {
            //Do something
            }
            else {
            //You have to call clearInterval() to stop the timer
            clearInterval(hungerTimer);
            }
            }


            Then use setInterval like this:



            //Using a variable to store the timer reference that we create
            hungerTimer = setInterval(updateHunger, 5000);


            Remember to declare the hungerTimer variable in a scope where it can be accessed from both updateHunger() and the method that calls setInterval().







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 20 '18 at 18:16









            RomenRomen

            1467




            1467























                0














                You have to first set a variable for setInterval and then stop the iteration with clearInterval (important, otherwise the loop will iterate indefinitely). And check for fullness to be greater than 0.



                var fullness = 10;
                var timer = setInterval(function(){
                if(fullness > 0){
                fullness--;
                }
                else{
                clearInterval(timer);
                }
                }, 5000);


                Here is the working jsFiddle






                share|improve this answer






























                  0














                  You have to first set a variable for setInterval and then stop the iteration with clearInterval (important, otherwise the loop will iterate indefinitely). And check for fullness to be greater than 0.



                  var fullness = 10;
                  var timer = setInterval(function(){
                  if(fullness > 0){
                  fullness--;
                  }
                  else{
                  clearInterval(timer);
                  }
                  }, 5000);


                  Here is the working jsFiddle






                  share|improve this answer




























                    0












                    0








                    0







                    You have to first set a variable for setInterval and then stop the iteration with clearInterval (important, otherwise the loop will iterate indefinitely). And check for fullness to be greater than 0.



                    var fullness = 10;
                    var timer = setInterval(function(){
                    if(fullness > 0){
                    fullness--;
                    }
                    else{
                    clearInterval(timer);
                    }
                    }, 5000);


                    Here is the working jsFiddle






                    share|improve this answer















                    You have to first set a variable for setInterval and then stop the iteration with clearInterval (important, otherwise the loop will iterate indefinitely). And check for fullness to be greater than 0.



                    var fullness = 10;
                    var timer = setInterval(function(){
                    if(fullness > 0){
                    fullness--;
                    }
                    else{
                    clearInterval(timer);
                    }
                    }, 5000);


                    Here is the working jsFiddle







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 20 '18 at 18:23

























                    answered Nov 20 '18 at 18:13









                    Nawed KhanNawed Khan

                    2,8241618




                    2,8241618























                        0














                        The reason you are bumping into this is that JS runs in a single thread. Blocking it by waiting for 1 second would make the entire browser stall, which is why JS does not allow it and we do not have sleep() in JS, we have the Timers API.



                        But it's nonetheless nice to write straight up for-loops that look synchronous because that's how we "normally" think. That's why you can actually nowadays write something like this if using an engine with async and generator support:



                        // ES6 features

                        const sleeper = (x, timeout) =>
                        new Promise(resolve => setTimeout(resolve, timeout, x));

                        function* timer(count, timeout) {
                        for (let i = count; i >= 0; i--) {
                        yield sleeper(i, timeout);
                        }
                        }

                        async function main() {
                        for (let i of timer(10, 1000)) {
                        console.log(await i); // Blocks the main() function but not the JS main thread!
                        }
                        }

                        main();
                        console.log("The call to main() was non-blocking");





                        share|improve this answer






























                          0














                          The reason you are bumping into this is that JS runs in a single thread. Blocking it by waiting for 1 second would make the entire browser stall, which is why JS does not allow it and we do not have sleep() in JS, we have the Timers API.



                          But it's nonetheless nice to write straight up for-loops that look synchronous because that's how we "normally" think. That's why you can actually nowadays write something like this if using an engine with async and generator support:



                          // ES6 features

                          const sleeper = (x, timeout) =>
                          new Promise(resolve => setTimeout(resolve, timeout, x));

                          function* timer(count, timeout) {
                          for (let i = count; i >= 0; i--) {
                          yield sleeper(i, timeout);
                          }
                          }

                          async function main() {
                          for (let i of timer(10, 1000)) {
                          console.log(await i); // Blocks the main() function but not the JS main thread!
                          }
                          }

                          main();
                          console.log("The call to main() was non-blocking");





                          share|improve this answer




























                            0












                            0








                            0







                            The reason you are bumping into this is that JS runs in a single thread. Blocking it by waiting for 1 second would make the entire browser stall, which is why JS does not allow it and we do not have sleep() in JS, we have the Timers API.



                            But it's nonetheless nice to write straight up for-loops that look synchronous because that's how we "normally" think. That's why you can actually nowadays write something like this if using an engine with async and generator support:



                            // ES6 features

                            const sleeper = (x, timeout) =>
                            new Promise(resolve => setTimeout(resolve, timeout, x));

                            function* timer(count, timeout) {
                            for (let i = count; i >= 0; i--) {
                            yield sleeper(i, timeout);
                            }
                            }

                            async function main() {
                            for (let i of timer(10, 1000)) {
                            console.log(await i); // Blocks the main() function but not the JS main thread!
                            }
                            }

                            main();
                            console.log("The call to main() was non-blocking");





                            share|improve this answer















                            The reason you are bumping into this is that JS runs in a single thread. Blocking it by waiting for 1 second would make the entire browser stall, which is why JS does not allow it and we do not have sleep() in JS, we have the Timers API.



                            But it's nonetheless nice to write straight up for-loops that look synchronous because that's how we "normally" think. That's why you can actually nowadays write something like this if using an engine with async and generator support:



                            // ES6 features

                            const sleeper = (x, timeout) =>
                            new Promise(resolve => setTimeout(resolve, timeout, x));

                            function* timer(count, timeout) {
                            for (let i = count; i >= 0; i--) {
                            yield sleeper(i, timeout);
                            }
                            }

                            async function main() {
                            for (let i of timer(10, 1000)) {
                            console.log(await i); // Blocks the main() function but not the JS main thread!
                            }
                            }

                            main();
                            console.log("The call to main() was non-blocking");






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 20 '18 at 20:01

























                            answered Nov 20 '18 at 19:54









                            Elias ToivanenElias Toivanen

                            1906




                            1906






























                                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%2f53398909%2fdecreasing-a-variable-by-increments-over-time-with-setinterval%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

                                Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

                                ComboBox Display Member on multiple fields

                                Is it possible to collect Nectar points via Trainline?