setTimeout Functionality in JavaScript

I’m trying to understand the concept of setTimeout and I couldn’t understand how it works. In the below example, when I gave the 1000 to the second setTimeout function I got the output as

1)Hello 567
2)Hello
3)Hello 123

But When I gave the setTimeout for all the functions as 0, it shows as

1)Hello 123
2)Hello 567
3)Hello

Initially, I assumed the innerfunction value is returned first then in the below case shouldn’t be

1)Hello 567
2)Hello 123
3)Hello

Please help me understand

<!DOCTYPE html>
<html>

<body>

  <p>Click the button to wait 3 seconds, then alert "Hello".</p>

  <button onclick="myFunction()">Try it</button>

  <script>
    function myFunction() {
      setTimeout(function() {
        alert("Hello");
      }, 0, setTimeout(function() {
        alert("Hello 123");
      }, 0), setTimeout(function() {
        alert("Hello 567");
      }, 0));
    }
  </script>

</body>

</html>

16 thoughts on “setTimeout Functionality in JavaScript”

Leave a Comment