Asynchronous Programming Flashcards
What is another word for sequential code?
synchronous code
describe sequential/synchronous code
The browser evaluates each line in this program, one at a time. For each line of code, the next line of code must wait until the current line completes.
Is this code sequential/synchronous?
function logger(object) { // 1
console.log(object); // 4 5 6 7
}
let numbers = [3, 7, 25, 39]; // 2
numbers.forEach(logger); // 3
console.log(numbers.length); // 8
Yes, still sequential
What happens?
// Be sure you run this code from a file!
setTimeout(function() {
console.log(‘!’);
}, 0);
setTimeout(function() {
console.log(‘World’);
}, 0);
console.log(‘Hello’);
Hello
!
World
For now, just realize that code being run by setTimeout only runs when JavaScript isn’t doing anything else. That means that your program must stop running before code executed with setTimeout will even begin to run. Even if your program runs for days at a time, any code executed by setTimeout will not run until your program has no more code to run. No matter how small the delay period, nothing will happen.
How to use setTimeout()
the arguments are:
handler/function/arguments
repeat a bit of code on a timer
setInterval(function, time)
cancel an interval after 4 seconds
setTimeout(clearInterval, 4000, purple);