My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Pause function execution for a certain time in javascript

Pause function execution for a certain time in javascript

Rajnish Katharotiya's photo
Rajnish Katharotiya
·Apr 19, 2020

Photo by NESA by Makers on Unsplash

Pausing function till one process ends is can be archive in various ways, well for some scenario what if we want to just pause our function for time or I say rest it a little while. how would you do it? 🤔

On the move, I would like to welcome you in a new episode of Javascript Useful Snippets where I'll share some shortcodes and function which will help you to make your code much efficient and neat. So, if you haven't read my previous episodes (articles) please check it out here or else stay tuned till the end to learn something new 😋 .

Are you familiar with word Promise? If you are not, I recommend the following post to check. ( see you in a bit 🤗 )

Now, I hope you know about the promises. so you'd figured out a way to make the process the waiting until one is not done. But guess you need to pause execution for a certain amount of time by just passing that certain time when you don't have any particular other processes dependent in that function, at those times this pause() function will work like charm.

The function needs just time(ms) as parameter argument and in return, it will hold execution for that given a time period. Let me share you a snippet now:-

const pause = ms => new Promise(resolve => setTimeout(resolve, ms));

Inside a function, I created Promise as mentioned in the above blog ( i hope you have read it ). and just used resolve callback as setTimeout(is a method to delay function for a time) callback and passed time as the second argument of it. So, resolve will trigger after that given amount of time.

How to use pause() function?

async function work() {
  console.log("Pausing execution for 1 second");
  await pause(1000);
  console.log('Resuming execution');
}

Need to create async function, and put pause in await when we call it. So, here i've passed 1000ms inside pause function which will hold execution for one second, as soon as we get success response from our promise it'll move to next execution.

Here, if anything goes wrong with the function we have put in await then further execution will be auto terminated so be careful to use. ( you can use try .... catch block in such cases ).

I was making animation and wanted to add a delay in transition, so I was using setTimeout repeatedly and there I figured to have a function like this to hold my execution for a certain time without hurdles. So, i thought to share it to you too. I hope you learned something, if yes, hit the follow button to learn everyday 😅