Review of Week 3 Day 1 Learning Objectives

  1. Identify JavaScript as a language that utilizes an event loop model
  2. Identify JavaScript as a single threaded language

JavaScript is a single threaded language, which can only run one statement of code at at a time.

The JavaScript runtime can only do one thing at a time. In order to write performant, responsive code we utilize callbacks in order to perform slow tasks asynchronously. This keeps the single thread free to run code that’s ready to run now.

The event loop facilitates the management of callbacks and asyncronous behaviour within the single threaded runtime.

Bonus video [25 min]: What the heck is the event loop anyway?

  1. Describe the difference between asynchronous and synchronous code

Synchronous code (often called iterative code) is code that runs in linear order, one expression following the next, from beginning to end.

Asynchronous code is code that we schedule to run later. Usually, we have to wait for some other code to complete before we can proceed with our current code, so we wrap it in a callback, and ask JavaScript to return asynchronously to our callback.

  1. Execute the asynchronous function setTimeout with a callback.
setTimeout(function() {
    console.log('TIME!');
}, 1000);
  1. Given the function
function asyncy(cb) {
    setTimeout(cb, 1000);
    console.log("async")
}

and the function

function callback() {
    console.log("callback");
}

predict the output of asyncy(callback);

> asyncy(callback);
'async'
'callback'
  1. Use setInterval to have a function execute 10 times with a 1 second period. After the 10th cycle, clear the interval.
function tenIntervals( ) {
    let count = 0;
    let handler = setInterval(function() {
        count++;
        console.log('execute');
        if (count == 10) {
            clearInterval(handler);
        }
    }, 1000);

}
tenIntervals();
  1. Write a program that accepts user input using Node’s readline module
const readline = require('readline');
    
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
    
rl.question('What would you like to say? ', (answer) => {
    console.log('You said: ' + answer);
    rl.close();
});