DEV Community

Ryan Ameri
Ryan Ameri

Posted on

Mastering Hard Parts of JavaScript: Asynchronicity II

Exercise 1

Thinking point (no writing code necessary for this challenge): Inspect the code given to you in Challenge 1. In what order should the console logs come out? Howdy first or Partnah first?

function sayHowdy() {

function testMe() {
  setTimeout(sayHowdy, 0);

Solution 1

The output is Partnah first, followed by Howdy. As discussed, setTimeout is a callback function so its execution gets placed in the task queue, it is invoked only after everything in the call stack is executed.

Exercise 2

Create a function delayedGreet that console logs welcome after 3 seconds.

function delayedGreet() {}

// should log (after 3 seconds): welcome

Solution 2

function delayedGreet() {
  setTimeout(() => console.log("welcome"), 3000);

A gentle introduction, but an important foundation. This is how to wrap a callback function (which in reality is not a browser API) in our own function.

Exercise 3

Create a function helloGoodbye that console logs hello right away, and good bye after 2 seconds.

function helloGoodbye() {}

// should log: hello should also log (after 3 seconds): good bye

Solution 3

function helloGoodbye() {
  setTimeout(() => console.log("good bye"), 3000);

Notice that we could have also written

function helloGoodbye() {
  setTimeout(() => console.log("good bye"), 3000);

The order doesn't matter in this example, as console.log will always get executed first before setTimeout is called.

Exercise 4

Create a function brokenRecord that console logs hi again every second. Use the End Code button to stop the console logs when you are satisfied that it is working.

function brokenRecord() {}
// should log (every second): hi again

Solution 4

function brokenRecord() {
  function printHi() {
    console.log("hi again");
  setInterval(printHi, 1000);

If you haven't seen setInterval before, you might be tempted to use a loop here but that won't get you the desired output. setInterval is a method of the Web APIs that the browser/environment provide. As always MDN is a fantastic way of delving into them all.

Exercise 5

Create a function limitedRepeat that console logs hi for now every second, but only for 5 seconds. Research how to use clearInterval if you are not sure how to do this.

function limitedRepeat() {}
// should log (every second, for 5 seconds): hi again

Solution 5

function limitedRepeat() {
  function printHi() {
    console.log("hi again");
  function clear() {
  const id = setInterval(printHi, 1000);
  setTimeout(clear, 5000);

And here is setInterval's counterpart: clearInterval. When we call setInterval, it returns an Interval ID which uniquely identifies the interval. We can pass that to clearInterval to stop the interval.

Top comments (0)