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>
setTimeoutis not correctly closed... you provide it more than 2 arguments, which will be evaluated as arguments to pass to the callback. I don't think you intended that.setTimeoutis used for? The outputHello 123, thenHello 567, thenHellomakes sense, since the inner arguments need to be evaluated before the outer function call. This is always the case and is not specific tosetTimeout. The only special thing aboutsetTimeoutis that a delay of0attempts to schedule function execution in the next event loop cycle.