How to Set a Function to Run Again After Certain Time in Javascript

Wait for a Function to Finish in JavaScript

  1. Sync and Async in JavaScript
  2. Apply callback to Look for a Function to Finish in JavaScript
  3. Utilize promises to Wait for a Function to Finish in JavaScript
  4. Utilise async/await to Wait for a Function to Cease Before Continuing Execution

This tutorial volition introduce JavaScript Callbacks, Promises, and Async/await and show yous how to wait for an async function to finish before continuing the execution.

To empathize what Promises and Async/look are, we start need to understand what the Sync and Async functions are in JavaScript.

Sync and Async in JavaScript

Synchronous programming executes one command at a time. When we phone call a office that performs a long-running action, information technology will stop the program until it finishes.

JavaScript is traditionally single-threaded, even with multi-cores. We tin go information technology to run tasks only on a single thread chosen the primary thread.

Such synchronous behavior is a limiting factor in the multi-threads merely helps the user write codes without worrying near concurrency bug.

While in asynchronous programming, the long-running activity will be executed in another thread other than the principal thread, so the primary execution is not blocked. When that long-running function finishes, the main program is informed and gets access to the results.

Most I/O primitives in JavaScript are non-blocking. Network requests, file systems operations are all non-blocking operations. Beingness blocked is the exception in JavaScript.

Since JavaScript is based on asynchronous programming techniques, there are multiple approaches such as callbacks, promises and async/await enabling you to put your functions executions in sequence. So that a code-block or a role won't be executed earlier another specific function finishes.

sync and async

The to a higher place effigy shows the clear variation betwixt asynchronous and synchronous execution of two functions.

Use callback to Expect for a Function to Stop in JavaScript

If we accept synchronous statements, so executing those statements afterwards each other is straight forrard.

          part ane(){     panel.log("I am part One"); } function Two(){     panel.log("I am role Two"); }  one(); Ii();                  

Output:

          I am part One  I am part Two                  

Suppose we want to execute two functions, functionOne() and functionTwo() such that functionOne() should be executed after executing some asynchronus statements inside functionTwo().

          office functionOne(_callback){     // practice some asynchronus work      _callback(); }  function functionTwo(){     // exercise some asynchronus work      functionOne(()=>{         console.log("I am a callback");     }); }  functionTwo();                  

When executing the above code, the terminal thing printed in the console is I am a callback. The famous callback instance is the setTimeout function with a handler office to execute after timing out.

          role testCallBack(){     console.log("log before use setTimeout function");     setTimeout(()=>{         console.log("within timeout");     },5000);     console.log("log after utilize setTimeout role"); }  testCallBack();                  

Output:

          log before employ setTimeout function log later use setTimeout function inside timeout                  

Utilise promises to Expect for a Office to Finish in JavaScript

A promise is an object representing the eventual fulfillment or failure of an asynchronous operation. Nosotros attach the fulfillment callback to the promise with one or more then statements, and when can call the mistake handler callback in the take hold of.

          doFirstThing() .so(effect => doSecondThing(issue)) .and so(newResult => doThirdThing(newResult)) .so(finalResult => {   console.log("The final result thing"+finalResult); }) .catch(failureCallbackfunction); }                  

To chain then and take hold of statements as the higher up example is one of the promises' advantages. We promise to doSecondThing(result) once the doFirstThing() is fulfilled. The arguments to the then are optional, but required if you have to render a consequence.

In instance there is an error, the browser will wait at the cease of the chain for the grab and execute it. Information technology is very similar to the famous endeavor-grab.

The following example will help us understand the promises bondage and show us how we can wait for a function with asynchronous behavior to end execution earlier we tin go on execution.

                      var resolvedFlag = truthful;  let mypromise = function functionOne(testInput){     console.log("Entered function");     render new Promise((resolve ,reject)=>{         setTimeout(             ()=>{                 console.log("Inside the promise");                 if(resolvedFlag==true){                     resolve("Resolved");                 }else{                     refuse("Rejected")                 }                  } , 2000         );     }); };  mypromise().then((res)=>{     panel.log(`The role recieved with value ${res}`) }).catch((error)=>{     panel.log(`Handling error as we received ${error}`); });                  

Output:

          Entered function Inside the promise The part received with value Resolved                  

Creating a hope can exist as easy as returning a new Promise(). The Promise() constructor receives a function as an argument, which should have 2 parameters - resolve and refuse.

In case our event is fulfilled, and we need to return the result, we use the resolve() part when succeeding in what we were doing. But if an error happens and needs to be handled, we utilize reject() to send the mistake to the catch.

Nosotros gear up the flag resolvedFlag = true to simulate mistake handling in the catch. If resolvedFlag is fix to be false, the reject() function is chosen, and the error is handled in the catch block.

Output:

          Entered function Inside the hope Handling fault equally we received Rejected                  

Use async/await to Wait for a Function to Finish Before Continuing Execution

Another style to wait for a function to execute before standing the execution in the asynchronous environment in JavaScript is to use async/wait.

The async function is the function that is declared by the async keyword, while only the await keyword is permitted inside the async function and used to suspend the progress inside the async part until the hope-based asynchronous operation is fulfilled or rejected.

The async and look keywords enable asynchronous, promise-based behavior in a cleaner style.

Let's understand how async/await works. The function we are waiting for should render an example of Promise class to expect for information technology to execute using the look keyword before calling it. Every bit mentioned above, the function that contains the await statement must be declared with the async statement.

The post-obit example shows how to wait for that promise-based function to finish earlier standing the execution.

          office testAsync(){     return new Hope((resolve,reject)=>{         //hither our function should be implemented          setTimeout(()=>{             console.log("Hullo from within the testAsync office");             resolve();         ;} , 5000         );     }); }  async part callerFun(){     console.log("Caller");     await testAsync();     console.log("After waiting"); }  callerFun();                  

Output:

          Caller Hullo from within the testAsync function Later waiting                  

Write for us

DelftStack articles are written by software geeks like you. If you besides would like to contribute to DelftStack by writing paid articles, you can bank check the write for us page.

Related Article - JavaScript Promises

  • Decode HTML Entities Using JavaScript
  • Wait for Promises to Get Resolved in JavaScript
  • seelylienly.blogspot.com

    Source: https://www.delftstack.com/howto/javascript/javascript-wait-for-function-to-finish/

    0 Response to "How to Set a Function to Run Again After Certain Time in Javascript"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel