Skip to content

Commit 9ba21a5

Browse files
authored
Adds some information about setTimeout() (mdn#8764)
1 parent b52e6a8 commit 9ba21a5

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

files/en-us/web/api/settimeout/index.html

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,31 @@ <h2>Description</h2>
6767
<p>To call a function repeatedly (e.g., every <em>N</em> milliseconds), consider using
6868
{{domxref("setInterval()")}}.</p>
6969

70+
<h3 id="asynchronous">Working with asynchronous functions</h3>
71+
72+
<p><code>setTimeout()</code> is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack.
73+
In other words, you cannot use <code>setTimeout()</code> to create a "pause" before the next function in the function stack fires.</p>
74+
75+
<p>See the following example:</p>
76+
<pre class="brush: js">
77+
setTimeout(() => {console.log("this is the first message")}, 5000);
78+
setTimeout(() => {console.log("this is the second message")}, 3000);
79+
setTimeout(() => {console.log("this is the third message")}, 1000);
80+
81+
// Output:
82+
83+
// this is the third message
84+
// this is the second message
85+
// this is the first message
86+
</pre>
87+
88+
<p>Notice that the first function does not create a 5-second "pause" before calling the second function. Instead, the first function is called, but waits 5 seconds to
89+
execute. While the first function is waiting to execute, the second function is called, and a 3-second wait is applied to the second function before it executes. Since neither
90+
the first nor the second function's timers have completed, the third function is called and completes its execution first. Then the second follows. Then finally the first function
91+
is executed after its timer finally completes.
92+
93+
<p>To create a progression in which one function only fires after the completion of another function, see the documentation on <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a>.
94+
7095
<h3 id="The_this_problem">The "this" problem</h3>
7196

7297
<p>When you pass a method to <code>setTimeout()</code>, it will be invoked with a <code>this</code> value that may differ from your

0 commit comments

Comments
 (0)