Javascript executes function immediately when passing arguments, undesired - javascript

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

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.

Can someone explain me the flow of functions in this example?

I looked at the above piece of code and tried my best to search for solutions and posted it here after giving it my all. This is my current understanding of the code:
debounce() is called when there is an input and onInput() is passed to it as a callback, and debounce function return another function , the function being returned takes an argument which is the function passed by the debounce() a.k.a the onInput() , I am stuck # func.apply(null , args);
1.Isn't func and args the same thing ????
Someone please explain step by step is possible..
debouce is only called once on the initial run, it creates and returns a new anonymous function - the actual event handler.
When the input event is triggered, the previously created function is executed and will call func (onInput) after 500ms. func is only once passed to debounce, but args are the actual input event arguments, which will be passed on to func via apply. In this case, apply is basically the same as func(...args); So func (aka onInput) will be called with the actual arguments from the input event after 500ms.
This is an example of debounce.
Debouncing is a practice which is used to improve browser performance.
A programming practice which ensure that time-consuming tasks do not fire so often.
It is used to limits the rate at which a function gets invoked.
I have explained debounce with example, please check out the link
debounce

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.

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 call a function on event

Please explain me the difference between these two statements. which one is calling the function 'connect'. connect is a user defined function.
`peer.on('connection', connect);`
and
f.on('open', function() {
connect(f);
});
Both will call connect when the event occurs. The main difference is that the first one gets its arguments set by the event subsystem since it is called directly by whatever manages the events. If your function either doesn't use any arguments or its arguments match up exactly with what the event system passes, then the first one works fine.
In the second one, you control the arguments sent to connect(f) so you can make the arguments anything you want. So, if you want to control the arguments yourself, then the second block of code gives you that option.
There really isn't much of a difference aside from example one using a named function as the callback and the second example using an anonymous function as the callback. Named callbacks are useful if you need to reuse them or if you just want to have more control over the organization of your callbacks.
Either way, the functions will be called after the execution of 'on' is complete.
For more information about callbacks have a look at http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

Categories

Resources