Calling `Function` vs `Function()` within the same function - javascript

I was writing a long polling script and ran into a too much recursion error which hung the browser. My goal is to call the same function every 1000ms using setTimeout(). Yes, I could use setInterval() but it is going to be a long polling script and will be waiting for a server response.
I fixed this by removing the () from the function I was calling within the same function.
My script looks like:
function messagePolling(){
console.log("polled")
setTimeout(messagePolling(),1000) // <--- removing `()` from the function works as intended
}
messagePolling();
What is the logic behind this? messagePolling is a function after all isn't it.

You're absolutely right - messagePolling is a function. However, messagePolling() is not a function. You can see that right in your console:
// assume messagePolling is a function that doesn't return anything
messagePolling() // -> undefined
So, when you do this:
setTimeout(messagePolling(), 1000)
You're really doing this:
setTimeout(undefined, 1000)
But when you do this:
setTimeout(messagePolling, 1000)
You're actually passing the function to setTimeout. Then setTimeout will know to run the function you passed - messagePolling - later on. It won't work if it decides to call undefined (the result of messagePolling()) later, right?

Written as
setTimeout(messagePolling(),1000) the function is executed immediately and a setTimeout is set to call undefined (the value returned by your function) after one second. (this should actually throw an error if ran inside Node.js, as undefined is not a valid function)
Written as setTimeout(messagePolling,1000) the setTimeout is set to call your function after one second.

When you type messagePolling you are passing the function to setTimeout as a parameter. This is the standard way to use setTimeout.
When you type messagePolling() you are executing the function and passing the return value to setTimeout
That being said, this code looks odd to me. This function just runs itself. It's going to keep running itself indefinitely if you do this.

Anywhere a function name contains "()" it is executed immediately except when it is wrapped in quotes i.e is a string.

Related

Javascript executes function immediately when passing arguments, undesired

When I run the code:
$(".pro-tip-1").mouseover(activateProTip(1));
It calls the function activateProTip right away. It doesn't wait for the mouseover to be a true scenario.
Now if I take out the argument (1) being passed, it runs as intended. It waits for mouseover to be true then it calls the function. This is what I want, however I also want to pass an argument.
$(".pro-tip-1").mouseover(activateProTip);
The problem is I can't seem to pass an argument and have it run as intended, but I want to be able to pass an argument.
I am completely new to Javascript if that isn't already obvious so please keep your code in response simple to follow, thanks in advance!
Try this solution it will work
$(".pro-tip-1").mouseover(()=>activateProTip(1));
Explanation:
you can use always callback function for click events.
when you calling like this(activateProTip(1)), this will not binding events, that's why it will call the immediatly
This is expected, the required argument is a function. If you instead pass a statement, it will be interpreted immediately (potentially you could have called a function which actually returns a function that you want to call on mouseover!). You can instead write a function that will then call activateProTip with the argument.
$(".pro-tip-1").mouseover(() => activateProTip(1));

Why does setTimeout require code to be enclosed in function?

In JavaScript, the setTimeout function requires code to be enclosed in a function.
Examples of invalid timeouts:
window.setTimeout(console.log('PING'),3000)
function ping(){console.log('PING')};window.setTimeout(ping(),3000)
Example of valid timeouts:
window.setTimeout(function(){console.log('PING')},3000)
function ping(){console.log('PING')};window.setTimeout(function(){ping()},3000)
Now my question: why? I understand why normal code might need to be enclosed in a function, but why is it ALWAYS necessary to enclose code in function(){}?
It doesn't always require an anonymous function. You can also pass a function reference as the first argument, for example, let's assume you have a function called log defined. You can validly write:
function log()
{
console.log( 'PING' );
}
window.setTimeout( log, 200 );
Notice that we don't pass the parentheses with the first argument here.
However, you're not able to pass parameters directly to log() in this instance, so it's necessary to wrap the function call inside an anonymous function.
The code is required to be enclosed in a function because, the setTimeout function does not execute individual lines of code. It takes two, arguments - the first argument is a callback function, and the second argument is the time in milliseconds. The callback function will be called by the setTimeout function internally after the specified amount of time passes.
In the example you gave
window.setTimeout(function(){console.log('PING')},3000)
you pass an anonymous function which would be called after 3000 milliseconds or 3 seconds.
Basically because setTimeout is an asynchronous operation and you need to give what to do next once the timeout is done (i.e. you give a callback function).
Unless JavaScript runtime could block the UI thread and resume execution once the setTimeout ends, you need to provide some executable code to perform an action once the asynchronous operation has been completed:
setTimeout(function() {
// Do stuff after 1 second
}, 1000);
In the other hand, what would be the point of giving a function return value as argument? Check this wrong code to be more illustrative:
// You do some action even BEFORE the timeout operation has been completed?
setTimeout(doStuff(), 1000);
Further reading
Callbacks in Wikipedia
It doesn't need to be enclosed in function(){} but it does need to be a parameter of type Function.
In the case of window.setTimeout(console.log('PING'),3000), what would happen is that console.log() would immediately be executed and the return value (which is undefined) would be passed to the setTimeout function. This code isn't passing a function as a parameter, it's passing the return value of a function as a parameter. Essentially, it's just a shorter way of writing this:
var retVal = console.log('PING'); // retVal === undefined
window.setTimeout(retVal,3000);
That's not special to setTimeout. console.log without () is a function, but console.log() means to invoke that function.
There are other methods to pass a function in to setTimeout, but the anonymous function is typically the cleanest.
Technically, this would work, too:
window.setTimeout(console.log,3000)
but it would not allow you to specify a parameter, making it rather useless here. This could be avoided by binding parameters:
window.setTimeout(console.log.bind(null,'PING'),3000)
In this case, bind is a function which is being invoked (as you can see by the fact it has parameters supplied), so just as before bind is immediately executed. However, bind is a function whose return value is itself a function, and it's that returned function that is passed to setTimeout and called three seconds later. This technique (which you will see used with bind, call, and apply) is called partial application which really just means that you transform a function taking some parameters into a function taking fewer parameters (in this case, zero parameters) by specifying the parameters now but executing the function later.
Because setTimeout is a function that takes two argument - a function, and a number of seconds before that function executes.
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
Parameters:
func: A function to be executed after the timer expires.
code: An
optional syntax allows you to include a string instead of a function,
which is compiled and executed when the timer expires. This syntax is
not recommended for the same reasons that make using eval() a security
risk.
delay: Optional The time, in milliseconds (thousandths of a
second), the timer should wait before the specified function or code
is executed. If this parameter is omitted, a value of 0 is used. Note
that the actual delay may be longer; see Reasons for delays longer
than specified below.
param1, ..., paramN Optional Additional
parameters which are passed through to the function specified by func
once the timer expires.
Apparently YOU can just use code, as per the second argument above, but I have never seen it done.

Javascript: setTimeout beahavior in this example [duplicate]

Simply put...
why does
setTimeout('playNote('+currentaudio.id+', '+noteTime+')', delay);
work perfectly, calling the function after the the specified delay, but
setTimeout(playNote(currentaudio.id,noteTime), delay);
calls the function playNote all at the same time?
(these setTimeout()s are in a for loop)
or, if my explanation is too hard to read, what is the difference between the two functions?
The first form that you list works, since it will evaluate a string at the end of delay. Using eval() is generally not a good idea, so you should avoid this.
The second method doesn't work, since you immediately execute a function object with the function call operator (). What ends up happening is that playNote is executed immediately if you use the form playNote(...), so nothing will happen at the end of the delay.
Instead, you have to pass an anonymous function to setTimeout, so the correct form is:
setTimeout(function() { playNote(currentaudio.id,noteTime) }, delay);
Note that you are passing setTimeout an entire function expression, so it will hold on to the anonymous function and only execute it at the end of the delay.
You can also pass setTimeout a reference, since a reference isn't executed immediately, but then you can't pass arguments:
setTimeout(playNote, delay);
Note:
For repeated events you can use setInterval() and you can set setInterval() to a variable and use the variable to stop the interval with clearInterval().
You say you use setTimeout() in a for loop. In many situations, it is better to use setTimeout() in a recursive function. This is because in a for loop, the variables used in the setTimeout() will not be the variables as they were when setTimeout() began, but the variables as they are after the delay when the function is fired.
Just use a recursive function to sidestep this entire problem.
Using recursion to deal with variable delay times:
// Set original delay
var delay = 500;
// Call the function for the first time, to begin the recursion.
playNote(xxx, yyy);
// The recursive function
function playNote(theId, theTime)
{
// Do whatever has to be done
// ...
// Have the function call itself again after a delay, if necessary
// you can modify the arguments that you use here. As an
// example I add 20 to theTime each time. You can also modify
// the delay. I add 1/2 a second to the delay each time as an example.
// You can use a condition to continue or stop the recursion
delay += 500;
if (condition)
{ setTimeout(function() { playNote(theID, theTime + 20) }, delay); }
}
Try this.
setTimeout(function() { playNote(currentaudio.id,noteTime) }, delay);
Don't use string-timeouts. It's effective an eval, which is a Bad Thing. It works because it's converting currentaudio.id and noteTime to the string representations of themselves and hiding it in the code. This only works as long as those values have toString()s that generate JavaScript literal syntax that will recreate the value, which is true for Number but not for much else.
setTimeout(playNote(currentaudio.id, noteTime), delay);
that's a function call. playNote is called immediately and the returned result of the function (probably undefined) is passed to setTimeout(), not what you want.
As other answers mention, you can use an inline function expression with a closure to reference currentaudio and noteTime:
setTimeout(function() {
playNote(currentaudio.id, noteTime);
}, delay);
However, if you're in a loop and currentaudio or noteTime is different each time around the loop, you've got the Closure Loop Problem: the same variable will be referenced in every timeout, so when they're called you'll get the same value each time, the value that was left in the variable when the loop finished earlier.
You can work around this with another closure, taking a copy of the variable's value for each iteration of the loop:
setTimeout(function() {
return function(currentaudio, noteTime) {
playNote(currentaudio.id, noteTime);
};
}(currentaudio, noteTime), delay);
but this is getting a bit ugly now. Better is Function#bind, which will partially-apply a function for you:
setTimeout(playNote.bind(window, currentaudio.id, noteTime), delay);
(window is for setting the value of this inside the function, which is a feature of bind() you don't need here.)
However this is an ECMAScript Fifth Edition feature which not all browsers support yet. So if you want to use it you have to first hack in support, eg.:
// Make ECMA262-5 Function#bind work on older browsers
//
if (!('bind' in Function.prototype)) {
Function.prototype.bind= function(owner) {
var that= this;
if (arguments.length<=1) {
return function() {
return that.apply(owner, arguments);
};
} else {
var args= Array.prototype.slice.call(arguments, 1);
return function() {
return that.apply(owner, arguments.length===0? args : args.concat(Array.prototype.slice.call(arguments)));
};
}
};
}
I literally created an account on this site to comment on Peter Ajtai's answer (currently highest voted), only to discover that you require 50 rep (whatever that is) to comment, so I'll do it as an answer since it's probably worth pointing out a couple things.
In his answer, he states the following:
You can also pass setTimeout a reference, since a reference isn't executed immediately, but then you can't pass arguments:
setTimeout(playNote, delay);
This isn't true. After giving setTimeout a function reference and delay amount, any additional arguments are parsed as arguments for the referenced function. The below would be better than wrapping a function call in a function.
setTimeout(playNote, delay, currentaudio.id, noteTime)
Always consult the docs.
That said, as Peter points out, a recursive function would be a good idea if you want to vary the delay between each playNote(), or consider using setInterval() if you want there to be the same delay between each playNote().
Also worth noting that if you want to parse the i of your for loop into a setTimeout(), you need to wrap it in a function, as detailed here.
It may help to understand when javascript executes code, and when it waits to execute something:
let foo2 = function foo(bar=baz()){ console.log(bar); return bar()}
The first thing javascript executes is the function constructor, and creates a function object. You can use either the function keyword syntax or the => syntax, and you get similar (but not identical) results.
The function just created is then assigned to the variable foo2
At this point nothing else has been run: no other functions called (neither baz nor bar, no values looked up, etc. However, the syntax has been checked inside the function.
If you were to pass foo or foo2 to setTimeout then after the timeout, it would call the function, the same as if you did foo(). (notice that no args are passed to foo. This is because setTimeout doesn't by default pass arguments, although it can, but those arguments get evaluated before the timeout expires, not when it expires.)
After foo is called, default arguments are evaluated. Since we called foo without passing arguments, the default for bar is evaluated. (This would not have happened if we passed an argument)
While evaluating the default argument for bar, first javascript looks for a variable named baz. If it finds one, it then tries to call it as a function. If that works, it saves the return value to bar.
Now the main body of the function is evaluated:
Javascript looks up the variable bar and then calls console.log with the result. This does not call bar. However, if it was instead called as bar(), then bar would run first, and then the return value of bar() would be passed to console.log instead. Notice that javascript gets the values of the arguments to a function it is calling before it calls the function, and even before it looks up the function to see if it exists and is indeed a function.
Javascript again looks up bar, and then it tries to call it as a function. If that works, the value is returned as the result of foo()
So, function bodies and default arguments are not called immediately, but everything else is. Similarly, if you do a function call (i.e. ()), then that function is executed immediately as well. However, you aren't required to call a function. Leaving off the parentheses will allow you to pass that function around and call it later. The downside of that, though, is that you can't specify the arguments you want the function to be called with. Also, javascript does everything inside the function parentheses before it calls the function or looks up the variable the function is stored in.
Because the second one you're telling it to call the playNote function first and then pass the return value from it to setTimeout.

Why is my function invoked before the timeout of setTimeout() occurs?

This doesn't seem right, but this is how Firefox appears to be acting.
setTimeout(print(),5000);
function print(){
console.log(1);
}
Before the 5 seconds are up, after a link is clicked and before the next page begins to render, 1 is printed to the console. Any ideas? Thanks!
Edit: retitled, to make it obvious that there is a bug in the example code, not in firefox behavior.
No, the problem is that you are executing the print function immediately. Remove the brackets so you pass the function object rather than execute it.
setTimeout(print,50000);
Firefox will call print when it gets an expression that calls it, such as print().
You are calling print and passing its return value (undefined) to setTimeout.
Drop the () to pass the function itself.

Javascript setTimeout ignoring time parameter

It's not the first time I've used setTimeout(), but I can't figure out what the problem is. The code part of the setTimeout() is executing correctly, but it is executing immediately without the delay. If anyone can see the problem, that would help. Here's the code:
if(token==1){
img1.src=ssImages[imgNum];
num1=0;
num2=10;
setTimeout('crossFade()',2500);
}
Are you sure this is the code? If it executes immediately there are usually two reasons:
The developer thought the time is specified in seconds - but 2500 is fine, that's 2.5 seconds.
He calls the function immediately (e.g. setTimeout(foo(), 1234));
But none of the reasons apply to your code so check the rest of the code if there are any other calls to that function.
Anyway, you should really pass a function instead of a string:
setTimeout(crossFade, 2500);
Or, if you need to specify any arguments:
setTimeout(function() {
crossFade(...);
}, 2500);
I agree with Theifmaster. The window. setTimeout method takes two arguments:
1) Function OR Expression
2) Time in ms
In your code you provide a string or an Expression :
setTimeout('crossFade()',....)
This is generally discouraged as with the use of eval. You should pass a function - either named:
setTimeout(crossFade,....)
OR as suggested anonymous:
setTimeout(function(){crossFade()},....
This is about all you can do to trouble shoot this code unless you provide an example ok jsfiddle for us to see the context this is called.

Categories

Resources