Search justacoding.blog. [Enter] to search. Click anywhere to close.

JavaScript Exercises for Beginners, Part 3: Timing Functions

Welcome to Part 3 of the JavaScript exercises for beginners series. In Part 1, we looked at exercises that revolved around the use of strings. In Part 2, it was arrays. This time — we’re going to look at JavaScript’s timing functions: setInterval and setTimeout.

As with the previous instalments, there are no prior requirements other than a basic understanding of JavaScript and it’s syntax. As stated, this time around we’ll be looking at setInterval and setTimeout. If you aren’t familiar with these functions, here’s a quick overview:

The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

setTimeout works a little differently:

…setTimeout() sets a timer which executes a function or specified piece of code once the timer expires.

You’ll also need to make use of clearInterval within these exercises, this function is used to stop your running timer(s).

Most of the exercises within this article assume a configuration similar to this:

// HTML
<button onclick="startTimer()">Start</button>
<button onclick="stopTimer()">Stop</button>

// JS
const startTimer = () => {
    // Your code
}
const stopTimer= () => {
    // Your code
}

So you’ll need a “Start” button and a “Stop” button, with the relevant functions attached to each.

So, let’s begin!

1. Start/stop a counting timer

First up, trigger a timer upon clicking the “Start” button. Clicking “Stop” should clear the timer entirely.

In this case, your timer should count upwards from 0, logging each number to the console, until stopped.

startTimer() // invoked via button press
// 0
// 1
// 2
// 3
// 4
// 5
stopTimer() // invoked via button press

2. Pause the timer

Now, instead of stopping the timer — pause it.

Hitting “Start” again should continue the counting from the previous value. Optionally, have a separate function which also stops/resets the timer entirely.

startTimer() // invoked via button press
// 0
// 1
// 2
pauseTimer() // invoked via button press
startTimer() // invoked via button press
// 3
// 4
// ..

3. Iterate over an array a specific number of times

After starting the timer, log each item in the array in order. Do this x number of times — determined by one of the arguments to the function.

Once every item in the array has been logged to the console the required number of times, stop and reset the timer automatically.

Your function should receive two arguments, the actual array to iterate over as well as the amount of times to repeat this process.

startTimer([3, 5, 10], 2) // invoked via button press
// 3
// 5
// 10
// 3
// 5
// 10

4. Iterate the array items – forwards then backwards!

Iterate an array from the beginning to the end. Once at the end — loop backwards until you’ve logged out the very first item again. Then stop automatically.

Your function should accept one argument, the array to be iterated over.

startTimer(["a", "b", "c"]) // invoked via button press
// a
// b
// c
// b
// a

5. Wait for a while, then count to a specific number

On clicking “Start”, after a delay of x seconds — start to count upwards from 0. Your function should accept 2 arguments.

The first argument determines the initial delay; the second argument determines the number to count up to once the delay ends.

startTimer(8, 4) // invoked via button press
// [ ... delay of 8 seconds ]
// 0
// 1
// 2
// 3
// 4

Where can I find more JavaScript exercises?

If you enjoyed the exercises in this article or you’d like to look at a different aspect of JavaScript, I’d recommending checking out both of the previous instalments:

Each instalment in the series deals with a different area of JavaScript. In future, we’ll tackle exercises revolving around other topics — such as working with the Date object, promises, regular expressions and so on.

Alternatively, if you’re looking for something more time-consuming, I’ve published a few articles that provide some interesting project ideas. Take a look through the other posts in the blog, too, hopefully you’ll find something that catches your eye!

For something a little trickier

So this article is obviously focussed primarily on JavaScript exercises for beginners, however — it’d be prudent not to reference this classic example of a timing problem, too!

This fairly (in)famous question is (seemingly) commonly asked in interviews by the likes of tech giants such as Google and Amazon:

What will the code below output?

const someArray = [1, 2, 3, 4, 5]

for (var i = 0; i < someArray.length; i++) {
    setTimeout(function() {
        console.log("Index: " + i + ", element: " + someArray[i])
    }, 1000)
}

Note that there’s a setTimeout call within a loop. What intricacies are involved here? Maybe the output isn’t what you expect…

Hint: if you think the order goes something like: 1, 2, 3, 4, 5 – that’s not correct!

You can read more about the question (and have a look at the solution) over here.

Thanks for reading!

Have any questions? Ping me over at @justacodingblog
← Back to blog