Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a callback to a function in javascript

Tags:

I have two javascript functions

function one () {    do something long... like writing jpgfile on disk }  function two () {    do something fast... like show the file } 

I call it (in jQuery) like this

 one ();  two (); 

Because function two needs the link file from function one, i need to be sure the execution is completed... so getting the function two in the callback of function one should be the trick.. but how to do that ?

note : I did put an alert ('aaa') between those two functions to let function one complete, and it worked fine... when the alert is commented (removed) nothing works anymore !

like image 997
menardmam Avatar asked Oct 07 '11 19:10

menardmam


People also ask

How do you pass a callback function in JavaScript?

Passing a function to another function or passing a function inside another function is known as a Callback Function. Syntax: function geekOne(z) { alert(z); } function geekTwo(a, callback) { callback(a); } prevfn(2, newfn);

Is callback a function in JavaScript?

A JavaScript callback is a function which is to be executed after another function has finished execution. A more formal definition would be - Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function.

What is a callback in JavaScript?

A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.

Are callbacks still used in JavaScript?

Yes. The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.


1 Answers

You only need to use a callback if you are doing something asynchronous, otherwise it doesn't matter how long something takes, the next function won't run until the first has finished.

A callback is just passing a function as an argument, and then calling it when done.

function one (callback) {    do something long... like writing jpgfile on disk    callback(); }  function two () {    do something fast... like show the file }  one(two); 

Obviously, if you are doing something asynchronous, then you need something that will tell you when it is finished (such as an event firing).

like image 153
Quentin Avatar answered Sep 17 '22 13:09

Quentin