On Github galicians / AsynchronousJsSlides
At MakersAcademy by Pablo
- Understanding what is asynchronous javascript
- A few short !== simple exercises
- Realising we didn’t understand point 1
- Concepts that play a role in async javascript
- Do I understand now the async pattern?
- Resources for those that say no
- Resources for those that say yes
Oh hey, these are some notes. They'll be hidden in your presentation, but you can see them if you open the speaker notes window (hit 's' on your keyboard).puts "puts in line one, Im the first one" sleep(2) puts "puts in line two"
puts in line one, Im the first one //waits 2 sec puts in line two
setTimeout( function() { console.log('Im the first console.log') } , 2000); console.log('Im the second console log');
Im the second console log //waits 2 sec Im the first console.log
“synchronous” means to define async
a synchronous friend
In programming, each statement in your code is executed one after the other.
HAVE YOU USED async javascript already?Using async javascript
setTimeout( function() { console.log('Im the first console.log') } , 2000); console.log('Im the second console log');
Im the second console log //wait 2 sec Im the first console.log
setTimeout(function, time) is a function that receives 2 parameters:
- the first parameter is another function
- the second parameter is a time in milliseconds
- and it will execute the function received as a first parameter after the time we pass as a second parameter
What is the output of this script?
setTimeout(function() { console.log('Im console.log in line one') } , 3000); setTimeout(function() { console.log('Im console.log in line two') } , 2000); console.log('console log in line three')
setTimeout(function() { console.log('Im console.log in line one') } , 3000); setTimeout(function() { console.log('Im console.log in line two') } , 2000); console.log('console log in line three')
console log in line three console log in line two console log in line one
What is the output of this script?
for(var i = 0; i < 5; i++) { console.log("Calling setTimeout for value: " + i); setTimeout( function() { console.log(i) }, 1000); };
Calling setTimeout for value: 0 Calling setTimeout for value: 1 Calling setTimeout for value: 2 Calling setTimeout for value: 3 Calling setTimeout for value: 4 //wait 2 seconds 5 5 5 5 5
Write the code that generates the following output:
Calling setTimeout for value: 0 Calling setTimeout for value: 1 Calling setTimeout for value: 2 Calling setTimeout for value: 3 Calling setTimeout for value: 4 0 1 2 3 4
for (var i = 0; i < 4; ++i) { wrappingTimeout(i); }; function wrappingTimeout(i) { console.log("Calling setTimeout for value: " + i); setTimeout(function() { console.log(i); }, 2000); };
but you need to understand Javascript, meaning:
understanding hoisting understanding scope understanding clousures and of course understanding the event loop ...