Could you please tell me how do I write a function to check whether a specific function has been called, how many times it was called - with or without parameter.
Thanking you in advance
#elclanrs's solution is really good, but there are multiple problems with it:
You need to call the tracker function instead of the original function. That means you need to change some of your original code in order to use it.
You need to store a reference to the tracker object to get count.
Here is a solution for those problems:
function track() {
var calls = [],
context = window,
funcName,
i = 0;
if (arguments.length === 1) {
context = window;
funcName = arguments[0];
} else {
context = arguments[0];
funcName = arguments[1];
}
var func = context[funcName];
context[funcName] = function () {
calls.push({
count: i++,
args: Array.prototype.slice.call(arguments)
});
return func.apply(context, arguments);
};
context[funcName].getCalls = function () {
return calls;
};
}
Usage example:
// The function we want to track.
function log(val) {
console.log(val);
}
// Start tracking the function
track('log');
// Normal usage of the function
log('Message 1');
log('Message 2');
// Print the collected data of the function
console.log(log.getCalls());
/*^
[ { count: 0, args: [ 'Message 1' ] },
{ count: 1, args: [ 'Message 2' ] } ]
*/
Note: if your function is not in the global context (for example: document.getElementById), you need to do something like:
track(document, 'getElementById');
You can then collect the data normally:
document.getElementById.getCalls()
Each function has a caller property defined. You can make like this
function callfn() {
if (callfn.caller == null) {
return ("The function was called from the top!");
} else
return ("This function's caller was " + callfn.caller);
}
}
try something like this
var counter = {};
counter.with_param = 0;
counter.without_param = 0;
function test(arg){
if(!arg){
counter.without_param = counter.without_param + 1;
}else{
counter.with_param = counter.with_param + 1;
}
}
test(1);
test(5);
test();
test();
test(6);
console.log('WITH PARAM ' + counter.with_param);//3
console.log('WITHOUT PARAM ' + counter.without_param);//2
console.log('TOTAL CALLING ' + (counter.with_param + counter.without_param));//5
You could make a function decorator that saves the count and arguments in a closure, something like:
// Helper to convert pseudo-arrays
// such as `arguments` to real arrays
var __slice = Array.prototype.slice;
// Higher-order function that
// returns a function that saves the count
// and arguments when called
function track(f) {
var i = 0; // count
var calls = []; // array to save the info
var fn = function() {
// Save arguments and incremented counter
calls.push({
count: i++,
args: __slice.call(arguments)
});
// Call the original function with arguments
// preserving the context, and return its value
return f.apply(this, arguments);
};
// A function, attached to the decorated function,
// that gets the info out of the closure
fn.count = function() {
return calls;
};
// Return decorated function to be used
return fn;
}
// Decorate a normal function
var add1 = track(function(x) {
return x + 1;
});
// Run the function 3 times
// Internally the decorated function will keep
// track of the count and arguments
add1(1);
add1(2);
add1(3);
// Using the `count` function of our decorated function
console.log(add1.count());
/*^
[ { count: 0, args: [ 1 ] },
{ count: 1, args: [ 2 ] },
{ count: 2, args: [ 3 ] } ]
*/
Related
Hi I'm trying to understand callbacks in javascript and have come across this code here from a tutorial that I'm following:
var EventEmitter = require('events');
var util = require('util');
function Greetr() {
this.greeting = 'Hello world!';
}
util.inherits(Greetr, EventEmitter);
Greetr.prototype.greet = function(data) {
console.log(this.greeting + ': ' + data);
this.emit('greet', data);
}
var greeter1 = new Greetr();
greeter1.on('greet', function(data) {
console.log('Someone greeted!: ' + data);
});
greeter1.greet('Tony');
Now I notice that the greeter1.on function takes a callback with a parameter. However I'm not sure how this is implemented internally. I tried looking through the nodejs event.js file but I'm still confused. I am aware that there are ways around this specific implementation by using an anonymous function wrapping the callback with parameters but I want to understand how to use the same format as above.
tldr: How can I create my own function that takes a callback and a parameter in the same fashion as greeter1.on above.
Thank you
Your function needs to define a new property on the current instance with the callback passed as an argument, so it can be called later, like so:
function YourClass () {
this.on = function(key, callback) {
this[key] = callback;
}
}
// Usage
const instance = new YourClass();
instance.on('eventName', function (arg1, arg2) {
console.log(arg1, arg2);
});
instance.eventName("First argument", "and Second argument")
// logs => First argument and Second argument
Callback is just passing a function as a parameter to another function and that being triggered. You can implement callback fashion as below
function test(message, callback) {
console.log(message);
callback();
}
//Pass function as parameter to another function which will trigger it at the end
test("Hello world", function () {
console.log("Sucessfully triggered callback")
})
class MyOwnEventHandler {
constructor() {
this.events = {};
}
emit(evt, ...params) {
if (!this.events[evt]) {
return;
}
for (let i = 0, l = this.events[evt].length; i < l; i++) {
if (!params) {
this.events[evt][i]();
continue;
}
this.events[evt][i](...params);
}
}
on(evt, eventFunc) {
if (!this.events[evt]) {
this.events[evt] = [];
}
this.events[evt].push(eventFunc);
}
}
var myHandler = new MyOwnEventHandler();
myHandler.on('test', function (...params) {
console.log(...params);
});
myHandler.emit('test', 'Hello', 'World');
I have some javascript codes as following:
require([url0],f0);
require([url1],f1);
require([url2],f2);
require([url3],f3);
f0,f1,f2, and f3 are four functions.
Now I have another line of instruction. I want to execute it after all the four functions have finished execution. Where should I put the instruction, or should I change the structure of the existing codes?
You can create your own function that takes multiple arguments and calls a callback when they are all loaded:
function requireMulti(data, doneFn) {
var numRemaining = data.length;
data.forEach(function(val, index) {
require([val.url], function() {
--numRemaining;
val.fn.apply(this, arguments);
if (numRemaining === 0) {
doneFn();
}
});
});
}
// sample usage
requireMulti([
{url: url0, fn: f0},
{url: url1, fn: f1},
{url: url2, fn: f2},
{url: url3, fn: f3},
], function() {
// everything is done here
});
You may consider taking a counter which initial value is 4 and a callback, wrapped in a class.
function CountDown(c, f) {
this.counter = c;
this.func = f;
this.dec = function () {
this.counter--;
if (!this.counter) {
this.func();
}
}
}
var counter = new CountDown(4, function () { alert('got all 4'); });
In all functions of f0 ... f3, you can include a snippet like
function f0() {
// code
counter.dec();
}
I need to create a function which can be executed only once, in each time after the first it won't be executed. I know from C++ and Java about static variables that can do the work but I would like to know if there is a more elegant way to do this?
If by "won't be executed" you mean "will do nothing when called more than once", you can create a closure:
var something = (function() {
var executed = false;
return function() {
if (!executed) {
executed = true;
// do something
}
};
})();
something(); // "do something" happens
something(); // nothing happens
In answer to a comment by #Vladloffe (now deleted): With a global variable, other code could reset the value of the "executed" flag (whatever name you pick for it). With a closure, other code has no way to do that, either accidentally or deliberately.
As other answers here point out, several libraries (such as Underscore and Ramda) have a little utility function (typically named once()[*]) that accepts a function as an argument and returns another function that calls the supplied function exactly once, regardless of how many times the returned function is called. The returned function also caches the value first returned by the supplied function and returns that on subsequent calls.
However, if you aren't using such a third-party library, but still want a utility function (rather than the nonce solution I offered above), it's easy enough to implement. The nicest version I've seen is this one posted by David Walsh:
function once(fn, context) {
var result;
return function() {
if (fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
I would be inclined to change fn = null; to fn = context = null;. There's no reason for the closure to maintain a reference to context once fn has been called.
Usage:
function something() { /* do something */ }
var one_something = once(something);
one_something(); // "do something" happens
one_something(); // nothing happens
[*] Be aware, though, that other libraries, such as this Drupal extension to jQuery, may have a function named once() that does something quite different.
Replace it with a reusable NOOP (no operation) function.
// this function does nothing
function noop() {};
function foo() {
foo = noop; // swap the functions
// do your thing
}
function bar() {
bar = noop; // swap the functions
// do your thing
}
Point to an empty function once it has been called:
function myFunc(){
myFunc = function(){}; // kill it as soon as it was called
console.log('call once and never again!'); // your stuff here
};
<button onClick=myFunc()>Call myFunc()</button>
Or, like so:
var myFunc = function func(){
if( myFunc.fired ) return;
myFunc.fired = true;
console.log('called once and never again!'); // your stuff here
};
// even if referenced & "renamed"
((refToMyfunc)=>{
setInterval(refToMyfunc, 1000);
})(myFunc)
UnderscoreJs has a function that does that, underscorejs.org/#once
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
};
Talking about static variables, this is a little bit like closure variant:
var once = function() {
if(once.done) return;
console.log('Doing this once!');
once.done = true;
};
once(); // Logs "Doing this once!"
once(); // Logs nothing
You could then reset a function if you wish:
once.done = false;
once(); // Logs "Doing this once!" again
You could simply have the function "remove itself"
function Once(){
console.log("run");
Once = undefined;
}
Once(); // run
Once(); // Uncaught TypeError: undefined is not a function
But this may not be the best answer if you don't want to be swallowing errors.
You could also do this:
function Once(){
console.log("run");
Once = function(){};
}
Once(); // run
Once(); // nothing happens
I need it to work like smart pointer, if there no elements from type A it can be executed, if there is one or more A elements the function can't be executed.
function Conditional(){
if (!<no elements from type A>) return;
// do stuff
}
var quit = false;
function something() {
if(quit) {
return;
}
quit = true;
... other code....
}
simple decorator that easy to write when you need
function one(func) {
return function () {
func && func.apply(this, arguments);
func = null;
}
}
using:
var initializer= one( _ =>{
console.log('initializing')
})
initializer() // 'initializing'
initializer() // nop
initializer() // nop
try this
var fun = (function() {
var called = false;
return function() {
if (!called) {
console.log("I called");
called = true;
}
}
})()
From some dude named Crockford... :)
function once(func) {
return function () {
var f = func;
func = null;
return f.apply(
this,
arguments
);
};
}
Reusable invalidate function which works with setInterval:
var myFunc = function (){
if (invalidate(arguments)) return;
console.log('called once and never again!'); // your stuff here
};
const invalidate = function(a) {
var fired = a.callee.fired;
a.callee.fired = true;
return fired;
}
setInterval(myFunc, 1000);
Try it on JSBin: https://jsbin.com/vicipar/edit?js,console
Variation of answer from Bunyk
Here is an example JSFiddle - http://jsfiddle.net/6yL6t/
And the code:
function hashCode(str) {
var hash = 0, i, chr, len;
if (str.length == 0) return hash;
for (i = 0, len = str.length; i < len; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
var onceHashes = {};
function once(func) {
var unique = hashCode(func.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1]);
if (!onceHashes[unique]) {
onceHashes[unique] = true;
func();
}
}
You could do:
for (var i=0; i<10; i++) {
once(function() {
alert(i);
});
}
And it will run only once :)
Initial setup:
var once = function( once_fn ) {
var ret, is_called;
// return new function which is our control function
// to make sure once_fn is only called once:
return function(arg1, arg2, arg3) {
if ( is_called ) return ret;
is_called = true;
// return the result from once_fn and store to so we can return it multiply times:
// you might wanna look at Function.prototype.apply:
ret = once_fn(arg1, arg2, arg3);
return ret;
};
}
If your using Node.js or writing JavaScript with browserify, consider the "once" npm module:
var once = require('once')
function load (file, cb) {
cb = once(cb)
loader.load('file')
loader.once('load', cb)
loader.once('error', cb)
}
If you want to be able to reuse the function in the future then this works well based on ed Hopp's code above (I realize that the original question didn't call for this extra feature!):
var something = (function() {
var executed = false;
return function(value) {
// if an argument is not present then
if(arguments.length == 0) {
if (!executed) {
executed = true;
//Do stuff here only once unless reset
console.log("Hello World!");
}
else return;
} else {
// otherwise allow the function to fire again
executed = value;
return;
}
}
})();
something();//Hello World!
something();
something();
console.log("Reset"); //Reset
something(false);
something();//Hello World!
something();
something();
The output look like:
Hello World!
Reset
Hello World!
A simple example for turning on light only once.
function turnOnLightOnce() {
let lightOn = false;
return function () {
if (!lightOn) {
console.log("Light is not on...Turning it on for first and last time");
lightOn = true;
}
};
}
const lightOn = turnOnLightOnce();
lightOn() // Light is not on...Turning it on for first and last time
lightOn()
lightOn()
lightOn()
lightOn()
https://codesandbox.io/s/javascript-forked-ojo0i?file=/index.js
This happens due to closure in JavaScript.
function once (fn1) {
var ran = false
var memo = null
var fn = function(...args) {
if(ran) {return memo}
ran = true
memo = fn1.apply(null, args)
return memo
}
return fn
}
I'm using typescript with node and it was #I Hate Lazy's answer that inspired me. I just assigned my function to a noop function.
let printName = (name: string) => {
console.log(name)
printName = () => {}
}
printName('Sophia') // Sophia
printName('Nico') // Nothing Happens
https://jsbin.com/yuzicek/edit?js,console
FOR EVENT HANDLER
If the function is a callback for an event listener, there is already a built-in option in the addEventListner method for just executing the callback once.
It can accept 3 parameters
Type
callback
options
options is an object that has a property called once
ex:
const button = document.getElementById('button');
const callbackFunc = () => {
alert('run')
}
button.addEventListener('click', callbackFunc, { once: true })
<button id="button">Click Once</button>
Trying to use underscore "once" function:
var initialize = _.once(createApplication);
initialize();
initialize();
// Application is only created once.
http://underscorejs.org/#once
var init = function() {
console.log("logges only once");
init = false;
};
if(init) { init(); }
/* next time executing init() will cause error because now init is
-equal to false, thus typing init will return false; */
if (!window.doesThisOnce){
function myFunction() {
// do something
window.doesThisOnce = true;
};
};
If you're using Ramda, you can use the function "once".
A quote from the documentation:
once Function
(a… → b) → (a… → b)
PARAMETERS
Added in v0.1.0
Accepts a function fn and returns a function that guards invocation of fn such that fn can only ever be called once, no matter how many times the returned function is invoked. The first value calculated is returned in subsequent invocations.
var addOneOnce = R.once(x => x + 1);
addOneOnce(10); //=> 11
addOneOnce(addOneOnce(50)); //=> 11
keep it as simple as possible
function sree(){
console.log('hey');
window.sree = _=>{};
}
You can see the result
JQuery allows to call the function only once using the method one():
let func = function() {
console.log('Calling just once!');
}
let elem = $('#example');
elem.one('click', func);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<p>Function that can be called only once</p>
<button id="example" >JQuery one()</button>
</div>
Implementation using JQuery method on():
let func = function(e) {
console.log('Calling just once!');
$(e.target).off(e.type, func)
}
let elem = $('#example');
elem.on('click', func);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<p>Function that can be called only once</p>
<button id="example" >JQuery on()</button>
</div>
Implementation using native JS:
let func = function(e) {
console.log('Calling just once!');
e.target.removeEventListener(e.type, func);
}
let elem = document.getElementById('example');
elem.addEventListener('click', func);
<div>
<p>Functions that can be called only once</p>
<button id="example" >ECMAScript addEventListener</button>
</div>
Tossing my hat in the ring for fun, added advantage of memoizing
const callOnce = (fn, i=0, memo) => () => i++ ? memo : (memo = fn());
// usage
const myExpensiveFunction = () => { return console.log('joe'),5; }
const memoed = callOnce(myExpensiveFunction);
memoed(); //logs "joe", returns 5
memoed(); // returns 5
memoed(); // returns 5
...
You can use IIFE. IIFE means Immediately Invoked Function Expression and the result is to call a function only once by the time is created.
Your code will be like this:
(function () {
//The code you want to execute only one time etc...
console.log("Hello world");
})()
Additionally, this way the data in the function remains encapsulated.
Of course and you can return values from the function and stored them into a new variable, by doing:
const/let value = (function () {
//The code you want to execute only one time etc...
const x = 10;
return x;
})()
function x()
{
let a=0;
return function check()
{
if(!a++)
{
console.log("This Function will execute Once.")
return;
}
console.log("You Can't Execute it For the Second Time.")
return;
}
}
z=x()
z() //Op - This Function will execute once
z() //OP - You can't Execute it for the second time.
I find it useful to just have a simple function that just returns true once, so you can keep the side effects higher up.
let once = () => !! (once = () => false);
once() // true
once() // false
Use like this:
if (once()) {
sideEffect()
}
This exploits the fact that you can coerce an assignment expression to return true while changing the same function into a function that returns false.
If you must have it execute a function, it can be adapted using a ternary:
let once = (x) => !! (once = () => false) ? x() : false;
Now it accepts a single function as an argument. Fun fact, the second false is never reached.
// This is how function in JavaScript can be called only once
let started = false;
if (!started) {
start() { // "do something" }
}
started = true;
}
I got some methods (methA, methB ...) that need to call the same method methMain in Javascript. This method methMain then need to fetch some data and when it is done do a callback to the method that called it (methA or MethB ...).
I can successfully create a pointer/reference to a method by using what is written here: How can I pass a reference to a function, with parameters?
That solution, and all others I have seen, does not seem to work in the current scope.
This code will not work:
function TestStructure() {
this.gotData = false;
//define functions
this.methA = function (parA) { };
this.methB = function (parb) { };
this.createFunctionPointer = function (func) { };
this.createFunctionPointer = function (func /*, 0..n args */) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
var allArguments = args.concat(Array.prototype.slice.call(arguments));
return func.apply(this, allArguments);
};
};
this.methA = function (parA) {
alert('gotData: ' + this.gotData + ', parA: ' + parA);
if (this.gotData == false) {
var fp = this.createFunctionPointer(this.methA, parA);
this.methMain(fp);
return;
}
//...do stuff with data
}
this.methB = function (parB) {
alert('gotData: ' + this.gotData + ', parB: ' + parB);
if (this.gotData == false) {
var fp = this.createFunctionPointer(this.methB, parB);
this.methMain(fp);
return;
}
//...do stuff with data
}
this.methMain = function (func) {
//...get some data with ajax
this.gotData = true;
//callback to function passed in as parameter
func();
}
}
var t = new TestStructure();
t.methA('test');
When methMain do a callback to func (methA or methB) the variable this.gotData will not be set.
Is there a solution for this problem or do I need to re-think the design?
I want to do this to get data with ajax without blocking with async: false.
I am not 100% sure but I think you can solve your problem by doing
this.createFunctionPointer = function (func /*, 0..n args */) {
var args = Array.prototype.slice.call(arguments, 1);
var that = this; //<<< here
return function () {
var allArguments = args.concat(Array.prototype.slice.call(arguments));
return func.apply(that, allArguments);
//here ^^^
};
};
This will cause your partially evaluated function to be called with the same this that created the function pointer. If you want a different scope just change whatever you pass to .apply.
All I need to do is to execute a callback function when my current function execution ends.
function LoadData()
{
alert('The data has been loaded');
//Call my callback with parameters. For example,
//callback(loadedData , currentObject);
}
A consumer for this function should be like this:
object.LoadData(success);
function success(loadedData , currentObject)
{
//Todo: some action here
}
How do I implement this?
Actually, your code will pretty much work as is, just declare your callback as an argument and you can call it directly using the argument name.
The basics
function doSomething(callback) {
// ...
// Call the callback
callback('stuff', 'goes', 'here');
}
function foo(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
}
doSomething(foo);
That will call doSomething, which will call foo, which will alert "stuff goes here".
Note that it's very important to pass the function reference (foo), rather than calling the function and passing its result (foo()). In your question, you do it properly, but it's just worth pointing out because it's a common error.
More advanced stuff
Sometimes you want to call the callback so it sees a specific value for this. You can easily do that with the JavaScript call function:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.call(this);
}
function foo() {
alert(this.name);
}
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Joe" via `foo`
You can also pass arguments:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback, salutation) {
// Call our callback, but using our own instance as the context
callback.call(this, salutation);
}
function foo(salutation) {
alert(salutation + " " + this.name);
}
var t = new Thing('Joe');
t.doSomething(foo, 'Hi'); // Alerts "Hi Joe" via `foo`
Sometimes it's useful to pass the arguments you want to give the callback as an array, rather than individually. You can use apply to do that:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.apply(this, ['Hi', 3, 2, 1]);
}
function foo(salutation, three, two, one) {
alert(salutation + " " + this.name + " - " + three + " " + two + " " + one);
}
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Hi Joe - 3 2 1" via `foo`
It is good practice to make sure the callback is an actual function before attempting to execute it:
if (callback && typeof(callback) === "function") {
callback();
}
My 2 cent. Same but different...
<script>
dosomething("blaha", function(){
alert("Yay just like jQuery callbacks!");
});
function dosomething(damsg, callback){
alert(damsg);
if(typeof callback == "function")
callback();
}
</script>
function loadData(callback) {
//execute other requirement
if(callback && typeof callback == "function"){
callback();
}
}
loadData(function(){
//execute callback
});
function callback(e){
return e;
}
var MyClass = {
method: function(args, callback){
console.log(args);
if(typeof callback == "function")
callback();
}
}
==============================================
MyClass.method("hello",function(){
console.log("world !");
});
==============================================
Result is:
hello world !
Some of the answers, while correct may be a little tricky to understand. Here is an example in layman's terms:
var users = ["Sam", "Ellie", "Bernie"];
function addUser(username, callback)
{
setTimeout(function()
{
users.push(username);
callback();
}, 200);
}
function getUsers()
{
setTimeout(function()
{
console.log(users);
}, 100);
}
addUser("Jake", getUsers);
The callback means, "Jake" is always added to the users before displaying the list of users with console.log.
Source (YouTube)
If you want to execute a function when something is done. One of a good solution is to listen to events.
For example, I'll implement a Dispatcher, a DispatcherEvent class with ES6,then:
let Notification = new Dispatcher()
Notification.on('Load data success', loadSuccessCallback)
const loadSuccessCallback = (data) =>{
...
}
//trigger a event whenever you got data by
Notification.dispatch('Load data success')
Dispatcher:
class Dispatcher{
constructor(){
this.events = {}
}
dispatch(eventName, data){
const event = this.events[eventName]
if(event){
event.fire(data)
}
}
//start listen event
on(eventName, callback){
let event = this.events[eventName]
if(!event){
event = new DispatcherEvent(eventName)
this.events[eventName] = event
}
event.registerCallback(callback)
}
//stop listen event
off(eventName, callback){
const event = this.events[eventName]
if(event){
delete this.events[eventName]
}
}
}
DispatcherEvent:
class DispatcherEvent{
constructor(eventName){
this.eventName = eventName
this.callbacks = []
}
registerCallback(callback){
this.callbacks.push(callback)
}
fire(data){
this.callbacks.forEach((callback=>{
callback(data)
}))
}
}
Happy coding!
p/s: My code is missing handle some error exceptions
When calling the callback function, we could use it like below:
consumingFunction(callbackFunctionName)
Example:
// Callback function only know the action,
// but don't know what's the data.
function callbackFunction(unknown) {
console.log(unknown);
}
// This is a consuming function.
function getInfo(thenCallback) {
// When we define the function we only know the data but not
// the action. The action will be deferred until excecuting.
var info = 'I know now';
if (typeof thenCallback === 'function') {
thenCallback(info);
}
}
// Start.
getInfo(callbackFunction); // I know now
This is the Codepend with full example.
function LoadData(callback)
{
alert('the data have been loaded');
callback(loadedData, currentObject);
}
function login(email, password, callback) {
//verify the user
const users = [
{ email: "abc#gmail.com", password: "123" },
{ email: "xyz#gmail.com", password: "xyz" }
];
const user = users.find(
(user) => user.email === email && user.password === password
);
callback(user);
`enter code here`}
function redirect(user) {
if (user) {
//user is successfully logged in
console.log("user is successfully logged in ");
} else {
console.log("Incorrect credentials ");
}
}
login("abc#gmail.com", "123", redirect);
I hope this example will help everyone who wants to know about the callback in JS
Try:
function LoadData (callback)
{
// ... Process whatever data
callback (loadedData, currentObject);
}
Functions are first class in JavaScript; you can just pass them around.