Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I want to call a function in a endless loop after a specified time. For some reason setIntervall doesn't work. Here is a little example:
function button_clicked() {
clearInterval(interval)
interval = setInterval(test(), 1000);
}
var i=1;
function test(){
$("#body").append("<h1>Hi"+i+"</h1>");
i++;
}
Only always when I click on the button (this button starts button_clicked) it writes Hi and the int in the output, but not after 1 second.
What do I wrong?
This doesn't do what you think:
setInterval(test(), 1000)
This calls test immediately and sets the interval to execute the return value of test, which is undefined.
In JavaScript functions are variables like any other. Pass the variable (the function reference) to setInterval, not an execution of the function:
setInterval(test, 1000)
setInterval takes a function as 1st parameter, and you're not passing it correctly, see:
interval = setInterval(test(), 1000);
replace with:
interval = setInterval(test, 1000);
Remove the parenthesis in your setInterval.
Call a function in Javascript many times after a specified time
Otherwise the function executes immediately
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
let unrealFunctionToUnderstand = () => {
let tryToUnderstandThis = () => 666;
console.log('I\'m calling once time! :D');
return tryToUnderstandThis;
}
let hardcoreLesson = unrealFunctionToUnderstand();
console.log(hardcoreLesson());
console.log(hardcoreLesson());
I cant understand this code, my friend send me this...
unrealFunctionToUnderstand is a function. When called it logs "I'm calling once time! :D".
It also returns another function (tryToUnderstandThis) when called.
After defining this function you are (1) calling it unrealFunctionToUnderstand(), then (2) assigning it's returned value (tryToUnderstandThis) to hardcoreLesson. Then you are calling hardcoreLesson (reference to tryToUnderstandThis) twice and logging the result.
So you are calling unrealFunctionToUnderstand once, and it logs "I'm calling once time! :D", then calling tryToUnderstandThis twice, and it logs "666" twice.
Can you notice how I "ran" this code on paper? This is how you answer questions like this yourself. You interpret the code the same way the browser would, on paper. It becomes easier to pinpoint language constructs you don't understand or know yet, so you can first learn / ask about those. Then, if you understand each part, it becomes clear what is executed and why.
everything in javascript is an object, including functions. Which means you can return a function from a function.
That is exactly what unrealFunctionToUnderstand() is - it is a function which returns a function.
So, you call it once:
let hardcoreLesson = unrealFunctionToUnderstand();
Hence the console output only displays once. And you now have a reference to a function which simply returns the value 666.
let tryToUnderstandThis = () => 666;
....
return tryToUnderstandThis;
When you execute that, you get back the response.
hardcoreLesson store the value return by this function unrealFunctionToUnderstand.
So unrealFunctionToUnderstand calling only one time.
as hardcoreLesson store the value it's shows 2 times as it's called two time.
If you are familiar with any other programming language like C or Java, then you will be familiar with the following syntax.
function functionName(argument1, argument2, ...) {
// function body
// return statement
}
The new version of javascript introduces the arrow operator => to reduce your effort of writing single line functions. This is similar to lamda/inline function used mostly for single line functions.
So if you have a following function
function increment (value) {
return value + 1;
}
you can replace it with
increment(value) => value + 1
The other answers should help you understand how the function are also objects and how it can be called in different ways.
Some helpful links
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I just started to learn javascript and programming overall. I found these examples and trying to figure out results of those two functions.
First:
(function(){
var x = y = 11;
})();
console.log("x = " + (typeof x !== 'undefined'));
console.log("y = " + (typeof y !== 'undefined'));
Results are true and false.
Is it because var x is declared with var keyword so it is local var and y is not?
and second example:
(function(){
console.log("a");
setTimeout(function(){console.log("x")}, 1000);
setTimeout(function(){console.log("y")}, 0);
console.log("b");
})();
Please explain me the second example?
If I got it right, setTimeout will wait for execution even if time is set to 0.
Thanks
First: Correct. If you'd remove the 'var' from the 'x'-declaration that variable would also be available outside the function scope.
Second: The javascript function 'setTimeout' starts an asynchronous operation. In other words, the passed function gets added at the end of the queue to be operated at a later time, even if the passed time is 0ms.
The 'console.log' functions run synchronously, so they always will be executed before the functions given with the 'setTimeout'-function.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I found this setTimeout() method example on W3 Schools and noticed something that I cannot explain. The example is:
myVar = setTimeout(alertFunc, 3000);
...which works fine. But when I change it to
myVar = setTimeout(alertFunc(), 3000);
...the alert triggers instantly. Why? Shouldn't it be the same?
shouldn´t it be the same?
No, not at all.
setTimeout(alertFunc, 3000) passes the value of alertFunc (a reference to a function) into setTimeout. setTimeout stores that function reference in order to call it three seconds later.
setTimeout(alertFunc(), 3000) calls alertFunc, immediately, and passes its return value into setTimeout. Exactly the way foo(bar()) calls bar and passes its return value into foo.
The setTimeout() accepts a function as a first parameter and the time as the second parameter. I hope you have heard of functions returning a function as well. So for that cases, you can also call the function there.
The moment you add () to any function, it calls it immediately. So you call the function and return nothing to execute to the setTimeout.
Case 1
setTimeout(myFunc, 3000);
Here you are passing the function itself to get executed after 3 seconds.
Case 2
setTimeout(myFunc(), 3000);
Here you are passing the function's executed return value to get executed after 3 seconds.
myVar = setTimeout(alertFunc(), 3000); is the same as:
aF = alertFunc(); myVar = setTimeout(aF, 3000);
From this you can see that alertFunc is called outside of setTimeout.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Basically what I'm trying to do boils down to
function a() {
// Do stuff that waits for things etc
b(a);
}
function b(f) {
f()
}
function a() { b(a); }; function b(f) { f(); }; a()
That will cause a too much recursion error after a while though. Apparently javascript doesn't support tail-recursion so that won't work either. I can't think of any way to use a loop here either since I don't want the code executed immediately. So any way to do this or is it impossible?
Also I apologize if this has been asked before, couldn't find anything that helped.
Edit: Also before anyone asks, no I'm not actually using setTimeout so setIntervall isn't an option.
Edit again: Alright hope this shows what I'm trying to do better. I need to call the same code after waiting for things to complete again without actually putting it in a loop and blocking the program.
Because each call to a() returns before the next invocation, there is no recursion going on. The runtime system repeatedly makes individual calls to the function, and there won't ever be more than one call going on at any given time.
Breaking it down:
Somewhere, your code calls a() to start the cycle
That call to a() "does stuff" and then invokes setTimeout()
The system arranges for the timeout, and that call returns immediately
The original call to a() completes
100 milliseconds later, the timer fires and the runtime invokes a()
The cycle just repeats after that.
edit Maybe I should be more explicit: the word recursion refers to a process wherein a function invokes itself (synchronously) either directly or indirectly. Like:
function fibonacci(n) {
return fibonacci(n - 1) + fibonacci(n - 2);
}
What we have in the code posted in the OP is quite different. There's no call to a() being made from within that function (unless the OP left out some important details). Instead, a reference to the function is being handed over to the system. The call via that reference won't take place until a long, long time after the original call has finished.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I need to create a function with a callback function, but the solutions I've found does not allow to set the function.
I'll explain:
this is the solution I've found:
function callbackFunction()
{
alert("hello world");
}
function myFunction(callback)
{
callback()
}
myFunction(callbackFunction()) /* this works */
this is what i need:
function myFunction(callback)
{
callback()
}
myFunction(function(){alert("hello world");}); /* this doesn't work */
Some ideas?
Thank you
myFunction(callbackFunction()) /* this works */
No it doesn't. At least not in the way you think it does. This is:
Invoking callbackFunction
Passing the result of callbackFunction to myFunction
You're probably getting an error from within myFunction when it tries to invoke callback since that's not a function. But you're ignoring that because you see the alert() and think it works. The alert() happened before myFunction was invoked.
You want to pass it as a function reference, not a function invocation:
myFunction(callbackFunction) /* this works */
This would produce the same visible result (the alert()) but in the expected order of operations and without the error.
myFunction(function(){alert("hello world");}); /* this doesn't work */
You sure about that? If that is indeed "not working" for you then there must be more to the problem that you're not sharing with us, because that code works as-is.