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

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.

Related

TypeError occurs upon inserting a working function into a setTimeout call

A snipit of code that I am using works perfectly when it contains the first line of code shown below. However, when I replace that line with the second line of code shown below, a "TypeError [ERR_INVALID_CALLBACK]: Callback must be a function" error is thrown. Any suggestions on what I might do to fix this problem? Thanks.
getData(body);
setTimeout(getData(body), 0);
JavaScript setTimeout(function[, delay, arg1, arg2, ...]) takes the name of the function you want to execute as its first argument. Emphasis on the name of the function. This means getData in your case instead of getData() or getData(body). The second argument is the time to wait for before the function executes. The next argument (or comma-separated list of arguments) are the argument you want to supply to your function in the order your function expect them. This means written correctly, your code should look like this: setTimeout(getData, 0, body).
Seeing that your setTimout function is not delayed at all by setting delay to 0, you could just call getData(body) normally and it will do its work. Just saying.

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));

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

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.

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.

setTimeout(fn(), delay) doesnt delay as expected

I must be missing something quite obvious here because something rather strange is happening
I have a bit of js code that goes pretty much like this
setTimeout(myFn(), 20000);
If I m correct when I hit that line, after 20 seconds myFn should run right?
in my case myFn is an ajax call and it happens quite fast ( not at 20seconds and I just dont understand why. Any ideas or pointers?
Try
setTimeout(myFn,20000);
When you say setTimeout(myFn(),20000) your telling it to evaluate myFn() and call the return value after 20 seconds.
The problem is that myFn() is a function call not function pointer.
You need to do:
setTimeout(myFn, 20000);
Otherwise the myFn will be run before the timer is set.
No, the correct line would be setTimeout(myFn, 20000);
In yours, you're actually calling the myFn without delay, on the same line, and its result is scheduled to run after 20 seconds.
Remove the (). If you put them, the function is called directly. Without them, it passed the function as argument.

Categories

Resources