DEV Community 👩‍💻👨‍💻

Velcruza
Velcruza

Posted on

Using setTimeOut() in JavaScript

Sometimes in your code delaying a function's actions can be really useful which is what I'm going to be talking about today!

Imagine the following piece of code:

console.log("Hey, ")
console.log("you?")
console.log("how ")
console.log("are ")
Enter fullscreen mode Exit fullscreen mode

This would return us "Hey, you?how are ". Which doesn't really make any sense. (Obviously, the simplest/quickest fix would be to just reorganize our console.log or even combine it into one line but try to keep an open mind). A JavaScript function called "setTimeOut()" allows us to delay a function's actions after a specified number of milliseconds. setTimeOut() usually takes in a callback function or an anonymous function as one of its parameters and a number as it's other parameter.
For example:

setTimeOut(() => {console.log("delayed message")}, 500)
Enter fullscreen mode Exit fullscreen mode

This would delay our "delayed message" by 500 milliseconds.

So, going back to our initial piece of code that we had used as our example. We can now use setTimeOut() on our console.log("you?") to make sure it gets delayed until after the other two messages have already been logged to our console:

console.log("Hey, ")
setTimeOut(() => {console.log("you?")}, 500)
console.log("how ")
console.log("are ")
Enter fullscreen mode Exit fullscreen mode

Now this should return us "Hey, how are you?".

This was just a simple example of how you can utilize the setTimeOut() function in JavaScript. One thing that I've used it for is delaying a function call until I have fetched all the data from a public api that I was then using in said function. There are many other ways that you can implement this function into your code (if needed) to help you out if you're struggling with anything rendering/executing/etc. before you actually want it to.

One note to make though: figuring out the exact amount of milliseconds you want something to be delayed by can be quite difficult which is a downside of this. In the example I used above, realistically our computer doesn't need 500ms to log the other three messages to our console, but to a human, this isn't very noticeable.

Hope you guys enjoyed my little post about setTimeOut() and hopefully this will be useful to you someday :) !

Top comments (0)

Have you saved a post on DEV?

Head to your Reading List to read and manage the posts you've saved.