Executing a function passed as an argument in Javascript?

I am trying to write a generic function that blocks the user interface when calling AJAX. What I'm trying to do is function A to run any other function passed as an argument. This is what I have so far:

function blockWhileLoading(fn, msg) { if (msg == null) { msg = 'Please wait while the next page is loaded...'; } $.blockUI( { message: '<h1>' + msg + '</h1>', css: { border: 'none', padding: '15px', backgroundColor: '#E3D9BA', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', color: '#4D2612' } }); $('body').scrollLeft(0); setTimeout(function() { eval(fn); $.unblockUI(); }, 1000); } 

Now, when the time comes to calculate the function, nothing happens. Is eval the wrong way to get a function to work?

+4
source share
4 answers

No, eval is used to turn a piece of string into JavaScript code at runtime. Just call fn() . This is a function.

This is what eval does:

 var myalert = "alert('test');"; eval(myalert); 

Equivalent:

 eval("alert('test');"); 
+5
source

Just use fn();

+4
source

Why not just use:

 fn(); 

Instead of eval .

0
source

If fn is passed as an object, not a string, a call to fn() should work.

0
source

Source: https://habr.com/ru/post/1301141/


All Articles