Why doesn't Javascript let me close up my function? - javascript

I dunno guys, this is a really weird one, but I might just be making a simple mistake and not even realizing it.
I'm sort of a newbie to Javascript, so I'm attempting to write a script that gets content from a PHP script (which returns only a number) and write that data to a div... but Javascript had other ideas. I'm testing on Chrome on Mac OS X, although it doesn't work on Safari either.
The following block is giving me problems:
function getContent() {
window.setInterval(function () {
$.get("get.php", function (data) {
$('#img').slideUp();
$('#div').html(data);
$('#div').slideDown();
}
}
}
Which is failing with:
Uncaught SyntaxError: Unexpected token }
on line 51, or line 8, for the purposes of this example.
Does anyone know why it would fail like this? Don't I need to close the brackets I open?

Your curly braces are OK, but you're missing a few parentheses:
function getContent() {
window.setInterval(function () {
$.get("get.php", function (data) {
$('#img').slideUp();
$('#div').html(data);
$('#div').slideDown();
}); //get - end statement
}, 4000); // setInterval - need another parameter, end statement
}

You're not closing the parentheses for your function calls. As Kobi said, you also need a third parameter for setInterval.
function getContent() {
window.setInterval(function () {
$.get("get.php", function (data) {
$('#img').slideUp();
$('#div').html(data);
$('#div').slideDown();
});
}, 1000);
}

The window.setInterval function has a following syntax:
window.setInterval(functionRef, timeout);
In your case the setInterval and $.get() function call are missing the closing parentheses ). It would be clear for you to write this in the following way:
function getContent() {
// success handler
var success = function() {
// declare the function first as "changeUI"
var changeUI = function() {
$('#img').slideUp();
$('#div').html(data);
$('#div').slideDown();
};
// call the setInterval passing the function
window.setInterval(changeUI, 2000);
};
// get the resource and call the "success" function on successful response
$.get("get.php", success);
}

your window.setInterval is missing a ) after the } on the second to last line

Related

TypeError: "listener" argument must be a function. Using npm pixelmatch in node JS [duplicate]

How do I pass a function as a parameter without the function executing in the "parent" function or using eval()? (Since I've read that it's insecure.)
I have this:
addContact(entityId, refreshContactList());
It works, but the problem is that refreshContactList fires when the function is called, rather than when it's used in the function.
I could get around it using eval(), but it's not the best practice, according to what I've read. How can I pass a function as a parameter in JavaScript?
You just need to remove the parenthesis:
addContact(entityId, refreshContactList);
This then passes the function without executing it first.
Here is an example:
function addContact(id, refreshCallback) {
refreshCallback();
// You can also pass arguments if you need to
// refreshCallback(id);
}
function refreshContactList() {
alert('Hello World');
}
addContact(1, refreshContactList);
If you want to pass a function, just reference it by name without the parentheses:
function foo(x) {
alert(x);
}
function bar(func) {
func("Hello World!");
}
//alerts "Hello World!"
bar(foo);
But sometimes you might want to pass a function with arguments included, but not have it called until the callback is invoked. To do this, when calling it, just wrap it in an anonymous function, like this:
function foo(x) {
alert(x);
}
function bar(func) {
func();
}
//alerts "Hello World!" (from within bar AFTER being passed)
bar(function(){ foo("Hello World!") });
If you prefer, you could also use the apply function and have a third parameter that is an array of the arguments, like such:
function eat(food1, food2) {
alert("I like to eat " + food1 + " and " + food2 );
}
function myFunc(callback, args) {
//do stuff
//...
//execute callback when finished
callback.apply(this, args);
}
//alerts "I like to eat pickles and peanut butter"
myFunc(eat, ["pickles", "peanut butter"]);
Example 1:
funct("z", function (x) { return x; });
function funct(a, foo){
foo(a) // this will return a
}
Example 2:
function foodemo(value){
return 'hello '+value;
}
function funct(a, foo){
alert(foo(a));
}
//call funct
funct('world!',foodemo); //=> 'hello world!'
look at this
To pass the function as parameter, simply remove the brackets!
function ToBeCalled(){
alert("I was called");
}
function iNeedParameter( paramFunc) {
//it is a good idea to check if the parameter is actually not null
//and that it is a function
if (paramFunc && (typeof paramFunc == "function")) {
paramFunc();
}
}
//this calls iNeedParameter and sends the other function to it
iNeedParameter(ToBeCalled);
The idea behind this is that a function is quite similar to a variable. Instead of writing
function ToBeCalled() { /* something */ }
you might as well write
var ToBeCalledVariable = function () { /* something */ }
There are minor differences between the two, but anyway - both of them are valid ways to define a function.
Now, if you define a function and explicitly assign it to a variable, it seems quite logical, that you can pass it as parameter to another function, and you don't need brackets:
anotherFunction(ToBeCalledVariable);
There is a phrase amongst JavaScript programmers: "Eval is Evil" so try to avoid it at all costs!
In addition to Steve Fenton's answer, you can also pass functions directly.
function addContact(entity, refreshFn) {
refreshFn();
}
function callAddContact() {
addContact("entity", function() { DoThis(); });
}
I chopped all my hair off with that issue. I couldn't make the examples above working, so I ended like :
function foo(blabla){
var func = new Function(blabla);
func();
}
// to call it, I just pass the js function I wanted as a string in the new one...
foo("alert('test')");
And that's working like a charm ... for what I needed at least. Hope it might help some.
I suggest to put the parameters in an array, and then split them up using the .apply() function. So now we can easily pass a function with lots of parameters and execute it in a simple way.
function addContact(parameters, refreshCallback) {
refreshCallback.apply(this, parameters);
}
function refreshContactList(int, int, string) {
alert(int + int);
console.log(string);
}
addContact([1,2,"str"], refreshContactList); //parameters should be putted in an array
You can also use eval() to do the same thing.
//A function to call
function needToBeCalled(p1, p2)
{
alert(p1+"="+p2);
}
//A function where needToBeCalled passed as an argument with necessary params
//Here params is comma separated string
function callAnotherFunction(aFunction, params)
{
eval(aFunction + "("+params+")");
}
//A function Call
callAnotherFunction("needToBeCalled", "10,20");
That's it. I was also looking for this solution and tried solutions provided in other answers but finally got it work from above example.
Here it's another approach :
function a(first,second)
{
return (second)(first);
}
a('Hello',function(e){alert(e+ ' world!');}); //=> Hello world
In fact, seems like a bit complicated, is not.
get method as a parameter:
function JS_method(_callBack) {
_callBack("called");
}
You can give as a parameter method:
JS_method(function (d) {
//Finally this will work.
alert(d)
});
The other answers do an excellent job describing what's going on, but one important "gotcha" is to make sure that whatever you pass through is indeed a reference to a function.
For instance, if you pass through a string instead of a function you'll get an error:
function function1(my_function_parameter){
my_function_parameter();
}
function function2(){
alert('Hello world');
}
function1(function2); //This will work
function1("function2"); //This breaks!
See JsFiddle
Some time when you need to deal with event handler so need to pass event too as an argument , most of the modern library like react, angular might need this.
I need to override OnSubmit function(function from third party library) with some custom validation on reactjs and I passed the function and event both like below
ORIGINALLY
<button className="img-submit" type="button" onClick=
{onSubmit}>Upload Image</button>
MADE A NEW FUNCTION upload and called passed onSubmit and event as arguments
<button className="img-submit" type="button" onClick={this.upload.bind(this,event,onSubmit)}>Upload Image</button>
upload(event,fn){
//custom codes are done here
fn(event);
}
By using ES6:
const invoke = (callback) => {
callback()
}
invoke(()=>{
console.log("Hello World");
})
If you can pass your whole function as string, this code may help you.
convertToFunc( "runThis('Micheal')" )
function convertToFunc( str) {
new Function( str )()
}
function runThis( name ){
console.log("Hello", name) // prints Hello Micheal
}
You can use a JSON as well to store and send JS functions.
Check the following:
var myJSON =
{
"myFunc1" : function (){
alert("a");
},
"myFunc2" : function (functionParameter){
functionParameter();
}
}
function main(){
myJSON.myFunc2(myJSON.myFunc1);
}
This will print 'a'.
The following has the same effect with the above:
var myFunc1 = function (){
alert('a');
}
var myFunc2 = function (functionParameter){
functionParameter();
}
function main(){
myFunc2(myFunc1);
}
Which is also has the same effect with the following:
function myFunc1(){
alert('a');
}
function myFunc2 (functionParameter){
functionParameter();
}
function main(){
myFunc2(myFunc1);
}
And a object paradigm using Class as object prototype:
function Class(){
this.myFunc1 = function(msg){
alert(msg);
}
this.myFunc2 = function(callBackParameter){
callBackParameter('message');
}
}
function main(){
var myClass = new Class();
myClass.myFunc2(myClass.myFunc1);
}

Closing showWaitScreenWithNoClose in SharePoint CSOM

I am creating a list using REST APIs. In my JavaScript code I have written something like this:
// If I declare 'waitDialog' then it is not get closed by
// calling 'waitDialog.close()'. Without any declaration it works.
var waitDialog;
function createList() {
// Show wait dialog
waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose("Please wait...", "Please wait...", 100, 300);
jQuery.ajax({
// List data
},
success: doSuccess,
error: doError
});
}
function doSuccess(data) {
waitDialog.close(); // Close wait dialog
}
function doError(data, errorCode, errorMessage) {
waitDialog.close(); // Close wait dialog
}
If I declare waitDialog with statement var waitDialog; then it does not work by calling waitDialog.close(). Without any declaration it works and the dialog is closed. I found this question which elaborates on the difference between using var, but nothing which would clarify this case.
Any idea why does it work without declaration and not with declaration?
I could not recreate your declaration issue.
One thing I noticed... I believe you need to pass the SP.UI.DialogResult enumerable to the close method
waitDialog.close(SP.UI.DialogResult.OK);
//show and hide waiting on it javascript
function waitMessage() {
window.parent.eval("window.waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Processing...', '', 90, 300);");
}
function closeMessage() {
if (window.frameElement != null) {
if (window.parent.waitDialog != null) {
window.parent.waitDialog.close();
}
}
}

Is it possible to determine whether a certain function may be called when a passed-in callback function is executed in JavaScript?

The question title basically says it all. I made this Fiddle to make it easy to test. Here's the code:
var test = function(callback) {
console.log("callback() might call alert()");
callback();
}
test(function() {
alert("one");
});
Converting a function to a string returns the source code, you can search that with a regular expression.
var test = function(callback) {
if (callback.toString().test(/\balert\s*\(/) {
console.log("callback might call alert()");
callback();
};
This isn't perfect, though. It won't work with:
var foo = alert;
test(function() {
foo("Fooled you!");
});
It could also get a false positive if alert( appears in a string.
You can redefine function alert
function alert(str) {
console.log('Somebody call alert:'+str);
}
But IMHO it can't be definitely checked before call.

javascript initial capital function error in browser

i have following function to make the value of control Initial capital.
ctrl.value = ctrl.value.toLowerCase().replace( /\b[a-z]/g , function {
return arguments[0].toUpperCase();
});
When i run this in browser i get the following error in console
SyntaxError: missing ( before formal parameters
whats wrong with the syntax.
Your function definition is missing the () parenthesis.
// -------------------------------------------------------------- vv
ctrl.value = ctrl.value.toLowerCase().replace(/\b[a-z]/g, function() {
return arguments[0].toUpperCase();
});
Solved by changing function { to function () {

Javascript function execution order

I am new to javascript and have a quick question. Say i have the following code:
function entryPoint()
{
callFunction(parameter);
}
function callFunction(parameter)
{
... //do something here
var anotherFunction = function () { isRun(true); };
}
My question is that when callFunction(parameter) is called, and the variable anotherFunction is declared, does isRun(true) actually execute during this instantiation? I am thinking it doesnt and the contents of the anotherFunction are only "stored" in the variable to be actually executed line by line when, somewhere down the line, the call anotherFunction() is made. Can anyone please clarify the function confusion?
It seems the confusion is this line of code
var anotherFunction = function () { isRun(true); };
This declares a variable of a function / lambda type. The lambda is declared it is not run. The code inside of it will not execute until you invoke it via the variable
anotherFunction(); // Now it runs
You almost described it perfectly.
anotherFunction just receives a reference to a newly created Function Object (yes, Functions are also Objects in this language) but it does not get executed.
You could execute it by calling
anotherFunction();
for instance.
You can write a simple test like so:
entryPoint();
function entryPoint()
{
alert("In entryPoint");
callFunction();
}
function callFunction()
{
alert("In callFunction");
var anotherFunction = function () { isRun(); };
}
function isRun()
{
alert("In isRun");
}
​
And, the answer is no, isRun() does not get called.

Categories