This question already has answers here:
Why can I use a function before it's defined in JavaScript?
(7 answers)
Closed 5 years ago.
I'm currently a teacher's assistant in a web development course. Today, a student asked for help with his homework, in which he'd used setInterval, passing as the first parameter a function which he didn't define until a few lines of code later. I told him that wouldn't work, as the function would be undefined by the time the interval setting code was reached.
To my surprise, it worked perfectly. I've been trying to research this and am coming up blank: does JavaScript actually wait until the first execution of the callback to even see if the function name passed to it exists? That seems so counter-intuitive, but I can't imagine any other reason it would have worked. Where can I find out more about this unexpected behavior?
It depends:
If its a function expression :
//callback not defined ( exists but undefined)
var callback=function(){};
//callback defined
If its a function declaration :
//callback is defined
function callback(){}
//callback is defined
This is called hoisting, so vars and functions are moved to the top.
It also depends on the passed function too:
setInterval(callback,0);//doesnt work, callback is *undefined* in this moment
setInterval(function(){ callback();},100);//does work as callback is just called before being referenced.
var callback=function(){};
Related
This question already has answers here:
React Function Calling Methods
(3 answers)
Closed 8 months ago.
I have noticed that (at least in React) there are different ways to call a function. I'd say:
onClick={myFunction}
onClick={myFunction()}
onClick={()=>myFunction}
onClick={()=>myFunction()} /*Not sure if I've seen this type*/
Being the case all are correct, what are the difference between them?
onClick={myFunction}
Assigns myFunction to onClick.
onClick={myFunction()}
Calls myFunction immediately and assigns the return value (which needs to be another function) to onClick.
This is often an error caused by people not understanding how () works and wanting the previous syntax.
onClick={()=>myFunction}
Creates a new function and assigns it to onClick.
The new function mentions myFunction but doesn't do anything with it. It is a noop.
It is always a mistake.
onClick={()=>myFunction()}
Creates a new function, which calls myFunction, and assigns it to onClick.
This is usually a waste of resources. It is useful only if myFunction would do something with the event object that onClick passes to the event handler when called and you want to prevent that.
If you were to pass arguments to myFunction (which this example does not) then it would be more generally useful.
This question already has answers here:
setTimeout calls function immediately instead of after delay
(2 answers)
Closed 4 years ago.
I am using the below code to play an audio file for every second, the audio file is a second long and it basically a tick. The code will run only once and then I see the error in the console. My intention is to make it run every second until something is achieve then I can clear the Interval. This is the error I am getting in the console
Uncaught SyntaxError: Unexpected identifier
setInterval (async)
This is my code:
$('select[name=notsound]').change(function(){
var h = $(this).val();
var tickAudio = new Audio('https://www.sample.com/sounds/'+h+'');
setInterval(tickAudio.play(),1000);
});
I am not sure why is this happening, I am sure that I have made some error which is causing this issue, as it was working before I thought of giving it a different approach. Thank you for reading my query. :)
Method play needs to be called in the context of the right object:
var cleartick = setInterval(tickAudio.play.bind(tickAudio),1000);
The second suggestion of #rmlan will also work.
Clearing interval is the same - you need not to call a function, but to pass a function reference to setTimeout:
setTimeout(clearInterval, 3000, cleartick);
setInterval/setTimeout have a convenient way of passing parameters to timer functions - as cleartick above.
You are currently "executing" the result of tickAudio.play() every second, instead of executing the function itself.
To remedy this, you can either pass the function as an object:
setInterval(tickAudio.play.bind(tickAudio),1000);
Or wrap the call in an anonymous function:
setInterval(function () { tickAudio.play() },1000);
This question already has answers here:
When to use () after a callback function name? [duplicate]
(5 answers)
Closed 6 years ago.
Well I'm starting with jQuery and I'm wondering what is the difference between writing a function with or without parentheses inside a function.
For example if I have the following function:
function test(){
alert("pen pineapple apple pen");
}
This:
$(document).ready(test);
and this:
$(document).ready(test());
both show the same result: "pen pineapple apple pen"
Putting parentheses () at the end of a function causes that function to be invoked immediately, and use its return value in the expression.
This code $(document).ready(test); is using test as a callback function. It essentially says: when the document becomes ready, call the function that I'm providing you with (test).
This code $(document).ready(test()); is immediately invoking the function test, having it return a value, and then passing that value to the ready method. It's possible that test is returning a different function here, which in turn will act as the required callback function. It could also just be an error though, with someone inadvertently including the parentheses when they shouldn't have.
This question already has answers here:
In JavaScript, does it make a difference if I call a function with parentheses?
(5 answers)
Closed 7 years ago.
I'm trying to understand why this code below executes my function as soon as the document is loaded:
var list = document.getElementsByTagName('li');
function yep() {
window.alert('yep');
}
list[0].onclick = yep();
But this does not:
list[0].onclick = yep;
Why does () make a difference when executing a function in this situation?
The parenthesis () execute function immediately. On your second line you are assigning the value of list[0].onclick to the function name but not executing it.
Putting () after a reference to a function means that you want to call the function. Leaving them off means you just want to work with the reference to the function as a value in and of itself.
yep is a reference to a function.
yep() is a directive telling the Javascript engine to execute the yep function.
That's why one executes immediately and the other does not.
This question already has answers here:
setTimeout ignores timeout? (Fires immediately) [duplicate]
(3 answers)
Closed 8 years ago.
I'm working on a Chrome extension to fetch tweets and I figured that I could use the setInterval() function to make the script run every minute. First I tried giving it the function like this:
setInterval(myFunction(), interval);
But it would only execute my script once.
Then out of curiosity I tried declaring the function in the setInterval() function like so:
setInterval(function() {body of my function}, interval);
And that works, but is not a very pretty solution, does anybody any other way of doing this or am I just going to have to deal with it?
Just remove the brackets from the first call. The reason for this is that you need to pass in the function, not the result of the function (what it returns).
When you write the function's name with brackets, it calls the function. When you exclude the brackets, it simply refers to the function like a variable, and so you can pass in your function to the setInterval() function.
setInterval(myFunction, interval);