What is setTimeout() in JavaScript and How To Use setTimeout synchronously?

Jam
2 min readJun 6, 2020

--

What is setTimeout():

setTimeout() executes a function once the timer expires.

Suppose, you want a to run code after 2 seconds, you can use setTimeout()

Syntax:

setTimeout(function[, delay]);

function: can be an anonymous function, or, you can run another function.

delay: is the number of milliseconds.

Anonymous function:

setTimeout(function(){// write your code hereconsole.log(“I was waiting for two seconds!”);}, 2000);

A variable that refers to a function:

var show_a_message = function(){console.log(“I was waiting for two seconds!”);};setTimeout(show_a_message, 2000);

These two examples above will run after 2000 milliseconds = 2 seconds.

setTimeout is asynchronous:

console.log(“1”);setTimeout(function(){ console.log(“2”); }, 2000);console.log(“3”);// output132

This above code will print “3” before “2”. Second Line will run after 2 seconds. setTimeout is asynchronous, so the last line will not wait for setTimeout.

Now the question is, how we can use setTimeout synchronously.

Use setTimeout synchronously:

I found two ways to do it:

  1. Using Callback
  2. Using await, promise

In this article, I will explain the Callback. the callback is popular for its simplicity.

How callback function works:

We will pass a function into a timeout as an argument, and our function will be executed after the timeout is executed.

Let’s see an example.

var print_two = function(call_back){setTimeout(function(){console.log(“2”);call_back();}, 2000);};// codeconsole.log(“1”);print_two(function(){ console.log(“3”); });// output123

So, how print_two function actually works:

print_two function accepts a function as an argument ( call_back ) and executes that argument function after the timeout.

Let’s understand line by line:

  1. inline 1: it prints “1”
  2. inline 2: it calls print_two function with an anonymous function as an argument
  3. in print_two function:
  4. setTimeout function print “2”, then
  5. run the callback function and prints “3”

So, with callback, you can use setTimeout synchronously.

Conclusion:

I tried to keep this article simple. So, I used simple examples. Using a callback function is not new. the callback is being used in many javascript libraries. google map javascript also uses callback.

You can also run setTimeout synchronously with await, promise. Wich, I will explain it in another article.

Thanks.

--

--

Jam

Software engineer | Full Stack Developer | Programmer | Designer & Entrepreneur