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.
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 is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm new to JavaScript and working on a coding challenge as part of a bootcamp application process.
The question requires writing a single function to accomplish a task.
Although I've looked far and wide, I've yet to come across an answer.
If I write a function that contains other, nested functions, would that still be considered one function?
If I write a function that contains other, nested functions, would that still be considered one function?
Yes. A function is an encapsulation unit, it's a blackbox. You can call it, and get results back, but how it is implemented does not matter when looking from outside. A function that modularises its internal implementation into multiple local function is indistinguishable from one that does not as long as it behaves the same.
Yes.
From a technical perspective you can't even write a function that doesn't call use nested functions. The act of declaring variables alone is going to call a chain of functions to allocate memory which in turn eventually calls functions in assembly which then calls functions in your processor to which calls functions to your memory driver which calls.
Similarly calling operators to set or manipulate your variables are function calls which are all layered APIS calling a chain of functions.
Suppose you write a function min that looks like this:
function min(a,b) {
return Math.min(a,b);
}
This is still a single function even though it is calling a global function.
The same logic applies if you write an internal function for a complex object
function min(data) {
var smallest = function(a,b) {
if (a.x<b.x) { return a;}
else if (a.y>b.y) { return b;}
else if (a.y<b.y) return a;
return b;
}
return smallest(data[0],data[b]);
}
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 7 years ago.
Improve this question
How to control which function JavaScript run first,
i don't always want that particular function run first but the other.
What to do?
Javascript is single threaded, whichever function that is called is being executed in that order. The only exception to this rule is how the event loop is being executed.
So a call to setTimeout or setInterval cannot give a real idea on which method will get called first. Even if you use a setTimeout with the same interval. In thoery, the first method should be executed first in the event queue but that might be subject to implementations.
If you want to synchronize evented function, you have a while range of tools and libraries that will just what you need.
The callback method can be used to call a continuation when some kind of work is finished. This pattern has been improved in a more complex datastructure called a Promise.
Promise are pretty much the same things as callbacks but they are syntactically nicer to use.
Callback:
function foo(id, callback){
//ajax.get('/data/' + id, callback)
ajax.get('/data/' + id, function (data) {
callback(data)
})
}
foo(id, function (data) {
alert(data)
})
Promise:
function foo(id) {
return promiseGet('/data' + id)
}
foo(4).then(function (data) {
alert(data)
})
The advantage of promises is that they can be chained and thus, you can use async apis, pretty much like usually sync apis. All of the "then" parts are going to be executed in the order you added them.
Here's the site of promisejs that does a quite good explanation of promises.
https://www.promisejs.org/
Use self invoking function expression
Eg:
(function (i) {
console.log(i):
})(5);
And make sure, this comes before any similar functions, including one in the external added script
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to figure out how to access a variable inside a .when.done function. here's the example:
var colviews = {
1: true,
2: true,
3: false
}
$.when( // run only -when- these script get loaded
$.getScript( "/mckinney_images/jquery.tablesorter.all.js" )).done(function(){
$(function(){
console.log(colviews); // How do I get the colviews variable here?
});
});
I have a basic understanding of scope but not sure how it applies inside a when function.
I have a basic understanding of scope
Good! So you know what scope is, how closures work and how var works.
…but not sure how it applies inside a when function.
Simple: It's no different! Yes, the done callback function is invoked asynchronously, but that doesn't change how scope works.
You just are getting the colviews variable there successfully (if it doesn't log the expected value, that means it was overwritten elsewhere or the callback is never called because $.getScript failed).
$.when does no magic (and in fact, in your example it's not needed at all, your code works the same when you omit it).
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
I was reading Chapter 4: Functions() of the book Javascript Enlightenment by Cody Lindley.
http://jsfiddle.net/4a860dkg/
I was playing around with functions and wanted to know why in the fiddle addNumbersA returns anonymous(num1, num2, /**/) rather than returning a function()
Can anyone tell me why does this happen?
EDIT:
1. What I want to ask is that why doesn't logging addNumbersA return me a function() as it must do.
2. When I use typeof(addNumbersA), I get a function and not a function() - whereas addNumbersB returns function().
Apologies if i'm not clear enough.
The reason console.log(addNumbersA); returns:
function anonymous(num1,num2
/**/) {
return num1 + num2
}
Is because its a functional expression. The function keyword, when used as an expression, can create a function value. A function value can do all the things that other values can do—you can use it in arbitrary expressions, not just call it. It is possible to store a function value in a new place, pass it as an argument to a function, and so on.
Similarly, console.log(addNumbersB); returns:
function (num1, num2) {
return num1 + num2;
}
You can test this out in chrome dev tools, perhaps some inspectors/js repls have different notations of shortcutting, such that you may not get EXACT output (ie. just get 'function()' in Firebug).
Function is a constructor for function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
When you define a function as an instance of Function constructor, it is not compiled but stored as a runtime string. That's why it shows up as a function definition and not as a function object.
They will function the same except because it is compiled at the time of execution, it only has the global closure and has no knowledge of the local closure except for its own local variables.
console.log(addNumbersB); // logs function() correct!
This will not run the function, which your are expecting.
This does:
console.log(addNumbersB(2,2)); // logs 4 correct!
The above returns 4 because we call the function and pass the two numbers which are then added by the function;
The first example you give is a method rarely used for normal day to day coding, it creates a function from a string that represents valid code.