Bootcamp
Search…
📅
Course Schedule
0: Language and Tooling Teaching Guide
1: Frontend Basics Teaching Guide
2: Backend Basics Teaching Guide
3: Backend Applications Teaching Guide
4: Backend Structure Teaching Guide
5: Full-Stack Applications Teaching Guide
6: Frontend Infrastructure Teaching Guide
7: React Teaching Guide
8: Advanced React Teaching Guide
9: Advanced Topics Teaching Guide
🧮
Algorithms Teaching Guide
💼
Interview Prep Teaching Guide
☺
User Experience Teaching Guide
1.4: setTimeout

Introduction

setTimeout uses a callback function to do something at a later time.
setTimeout, just like addEventListener, takes a function passed as a parameter and executes that function asynchronously at a later time, specified by the second parameter.
1
console.log('starting...');
2
​
3
const delayInMilliseconds = 1000; // this is one second
4
​
5
const doLater = () => {
6
console.log('i happen later!');
7
};
8
​
9
setTimeout(doLater, delayInMilliseconds);
10
​
11
console.log('bananas!');
Copied!
If we aren't reusing the function anywhere else we can move it directly into the setTimeout function call.
1
console.log('starting...');
2
​
3
const delayInMilliseconds = 1000; // this is one second
4
​
5
setTimeout(() => {
6
console.log('i happen later!');
7
}, delayInMilliseconds);
8
​
9
console.log('bananas!');
Copied!

DOM Manipulation with setTimeout

1
const wowParagraph = document.createElement('p');
2
document.body.appendChild(wowParagraph);
3
​
4
const doLater = () => {
5
wowParagraph.innerText = `cool! ${Math.random()}`;
6
};
7
​
8
const myNewMain = (event) => {
9
console.log('hey wow my new function');
10
setTimeout(doLater, 1000);
11
};
12
​
13
wowParagraph.addEventListener('click', myNewMain);
Copied!

Exercise

Copy this code into script.js. Before you run it, read it carefully and decide what order you think the console.logs will come out it.
When you run the code, compare what you thought happened to what happened. Is it the same or not? Why or why not?
1
console.log('setTimeout! - 1');
2
​
3
const delayInMilliseconds = 1000; // this is one second
4
​
5
console.log('setTimeout! - 2');
6
​
7
const doLater = () => {
8
console.log('setTimeout! - 3');
9
};
10
​
11
console.log('setTimeout! - 4');
12
​
13
setTimeout(doLater, delayInMilliseconds);
14
​
15
console.log('setTimeout! - 5');
Copied!
Last modified 12d ago