You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: files/en-us/web/api/settimeout/index.html
+25Lines changed: 25 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -67,6 +67,31 @@ <h2>Description</h2>
67
67
<p>To call a function repeatedly (e.g., every <em>N</em> milliseconds), consider using
68
68
{{domxref("setInterval()")}}.</p>
69
69
70
+
<h3id="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
+
<preclass="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 <ahref="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a>.
94
+
70
95
<h3id="The_this_problem">The "this" problem</h3>
71
96
72
97
<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