Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Last active May 16, 2019 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harrisonmalone/1f4580d8b8d6d06742b6ec67d226f670 to your computer and use it in GitHub Desktop.
Save harrisonmalone/1f4580d8b8d6d06742b6ec67d226f670 to your computer and use it in GitHub Desktop.

Lecture ✍️

What is a callback

A callback is a function passed as an argument to a method call.

This might seem super weird right now but you'll get used to it. Callbacks are everywhere in javascript so it's the kind of thing that you just have to accept.

You've already been using callbacks in your array methods challenge yesterday.

const arr = [1,2,3,4]
arr.forEach((num) => {
  console.log(num)
})

Let's explain line by line what's happening here.

We define an array. On that array we can call the array method .forEach. The .forEach method takes a callback as an argument. The .forEach method is a method written for us by the people who implemented javascript. What's actually happening under the hood of .forEach would be some kind of while loop that keeps invoking the callback every time the next while loop passes through (until the end of the length of the array).

Think back to that lesson I gave you on yield in ruby. This is a very similar concept!

Again I'll reiterate that callbacks are every where in javascript. You can kind of ignore yield in ruby as it's not a requirement to solve most fundamental problems. This is not the case with callbacks; they're a requirement to solve fundamental javascript problems.

Writing your own callback methods

Here's an example of a callback in action.

const myFunc = (callbackFunc, num) => {
  const exp = 2
  return callbackFunc(exp, num)
}

const result = myFunc((exp, num) => {
  return num ** exp
}, 5)

console.log(result)

The first thing that runs in this example is the invoking of myFunc; the first argument is a function and the second argument is a number. So myFunc runs and we go into the function body. We set the variable exp to be equal to 2. We then return and invoke the callbackFunc with the arguments of the exp we defined previously and the num we passed as an argument previously (5). So we're now inside of the callback function; where we return the num (5) to the power of the exp (2). This equals 25 and we store this value in the variable result. We then console.log result.

Using setTimeout and setInterval

The javascript methods setTimeout and setInterval are special methods that both take two arguments; the first being a callback function and the second being an amount of time (specified in milliseconds).

Let's start with setTimout; it's a method that waits for the amount of time you specify as the second argument before invoking the callback function.

An example:

// this method will wait 3 seconds before console logging hello 
setTimeout(() => {
  console.log('hello')
}, 3000)

The method setInterval is similar in that it waits the specified amount of time before invoking but it also keeps invoking every interval (it never stops unless you tell it too).

// this method will wait 3 seconds before console logging hello, and will continue to console log hello every three seconds 
setInterval(() => {
  console.log('hello')
}, 3000)

Asynchronous vs synchronous javascript

It's time we start talking about one of the biggest reasons people love (and hate) javascript. This is because of it's ability to interchangeable switch between being synchronous and asynchronous.

So, what is synchronous code?

Synchronous code is what we've done is ruby thus far. The code executes line by line in a very defined order. If it has to wait for a process to finish (say a massively long while loop) it will wait for this process to finish.

This is synchronous javascript code.

let num = 0
const arr = []
while (num < 100000000) {
  arr.push(num)
  num += 1
}
console.log(arr)

Asynchronous code is where the code does not execute line by line. It executes what it can at that point in time independent of the line by line order.

Take this for example.

console.log('hello world')
setTimeout(() => {
  console.log('hello')
}, 3000)
console.log('after the setTimeout)

When you run this code see how the "after the setTimout" prints straight away even though it's after the setTimout in line by line order.

This is asynchronous javascript code.

// 1) Complete the callback boilerplate found here https://github.com/batteries76/js-fundamentals-path/blob/master/3-callback-boilerplate.js
// 2) Create a new directory and npm init, install moment.js as an npm package https://momentjs.com/docs/
// 3) Read through the moment.js documentation display section https://momentjs.com/docs/#/displaying/, write a function that console.logs the current time in this format (hours | minutes | seconds)
// 4) Using setInterval write a function that console.logs hello every 1 second (1000 milliseconds)
// 5) Using setInterval write a function that console.logs a command line clock, i want it to look exactly like this https://www.dropbox.com/s/gmq435z7f7sgwn3/clock.mov?dl=0
// 6) Create a count down from 10 using setInterval and clearInterval (look this up), the count down should display a message in the console when it reaches 0, it should look exactly like this https://www.dropbox.com/s/gffo858u7di3720/countdown.mov?dl=0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment