Code With Mark
Home
About
Resources
Contact

JavaScript Callback Functions

One of the good things and down fall about javascript is that it executes line by line. If you are waiting on external source ( like api call ) to finish processing, then this line by line processing data could present a major problem for you as some of your code may fail. Has this happened to you before? If so, read on to learn how to solve this problem.

One of the good things and down fall about javascript is that it executes line by line. If you are waiting on external source ( like api call ) to finish processing, then this line by line processing data could present a major problem for you as some of your code may fail.

Has this happened to you before? If so, read on to learn how to solve this problem.

You can easily solve your above problem with javascript callback functions.

Check Out The Training Video

What is a javascript callback function?

A callback function does a series of calculations just like you would do in a regular javascript function, however with callback function, the JavaScript will not continue until the callback function has finished doing its thing.

How do I use it ?

The easiest way to use callback is as follow:

//Create callback function
function call_back_func(callback)
{
 var d = 1;
 
 callback(d); //<---where the magic happens
}

//Call the callback function like this:
call_back_func(function(data)
{
 //data is here is value of variable d
 //in this case it will be 1
 console.log(data)
});

When To Use Regular Vs Callback Function?

When you are having to deal with any kind of calculation locally, always use a function that returns a value.

For example:

//Create function
function reg_func()
{
 var d = 100;
 
 return d; 
}

//Call the function like this:
 var v1 = reg_func();
 console.log(v1)

When you are making a call to an external source, always use a callback function, because that way your code will not continue until that process of external source has finished doing whatever it needs to do.

Check Out The Training Video

For Web Developers

Stop Building Websites That Pay You Once.

Use Shiply CMS to launch websites faster, manage clients easier, and turn every project into recurring monthly income.

Start Building Faster 🚀 Download Shiply CMS
How To Create A Secure Login System With PHP And MySQLHow To Create A Secure Login System With PHP And MySQL←Previous
My Short URL SystemMy Short URL SystemNext→

Related Posts

  • How Google Developers Think (And Why You Should Too)
  • Add Google Sign-In in 2 Minutes
  • Form Validation in 1 Line

Top Posts Viewed

Using JavaScript Window Onload Event Correctly
68 views
How Google Developers Think (And Why You Should Too)
58 views
Learn To Create YouTube Video Downloader
57 views

Categories

Courses
Excel
Google Script
Javascript
jQuery
Microsoft Access
MongoDB
Node JS
PHP
Quick Tip
Uncategorized
Wordpress