As part of the web app I'm building, multiple commands can come in from the server at once.
When these commands are processed, data will tend to be updated and then fairly heavy page HTML generation can occur.
At the moment when multiple similar commands come in, the program will process the data, then parts of the page are regenerated each time. This can lead to a lot of wasted processing time.
As such, I'm trying to make a callstack, so when a command is processed it looks to see if the function that the command triggers is in the stack and if it isn't found it adds it.
My problem is with keeping the called function from the callstack in the correct scope while also being able to eliminate duplicates.
Base Code:
var tools = {
functions:{
function1: function(){
return this;
},
function2: function(){
}
},
unique: function(arr){
var returnArr=[],
x, i;
for (x=0; x<arr.length; x++){
for (i=(x+1); i<arr.length; i++){
if (arr[x]===arr[i]){
arr.splice(i, 1);
}
}
returnArr.push(arr[x]);
}
return returnArr;
}
}
Example 1:
var callstack=[tools.functions.function1, tools.functions.function1];
callstack = tools.unique(callstack);
for (var x=0; x<callstack.length; x++){
console.log(callstack[x](), "should equal tools.functions");
}
This fails as "this" will return [function()]
Example 2:
var callstack=[
(function(){return tools.functions.function1()}),
(function(){return tools.functions.function1()})
];
callstack = tools.unique(callstack);
for (var x=0; x<callstack.length; x++){
console.log(callstack[x](), "should equal tools.functions");
}
This fails because you can't ensure that the functions are unique, so it'll still run the function twice.
This can be worked around by using two arrays (one that keeps track of the names of the functions, one that holds the encapsulated functions) and keeping them in sync, but I can't help but feel there must be a cleaner way using .call but I can't see it.
JSFiddle: http://jsfiddle.net/Kj6E8/
Generically speaking it is impossible to preserve the value of this in the way that you require. As soon as you push those functions into the array, the object that those functions once resided on is lost.
If you are only calling functions on a single object, you need to bind your functions to that object in some way. There are many ways of doing that, for example, you could pass the object to bind those function to in your unique function.
http://jsfiddle.net/8WAZb/1/
var tools = {
functions:{
function1: function(){
return this;
},
function2: function(){
}
},
unique: function(arr, o){
var returnArr=[],
x, i;
for (x=0; x<arr.length; x++){
for (i=(x+1); i<arr.length; i++){
if (arr[x]===arr[i]){
arr.splice(i, 1);
}
}
returnArr.push(this.bind(arr[x], o));
}
return returnArr;
},
bind: function(f, o) {
return function () {
return f.apply(o, arguments);
}
}
}
console.info("Example 1:");
var callstack=[tools.functions.function1, tools.functions.function1];
callstack = tools.unique(callstack, tools.functions);
console.log("Callstack:",callstack);
for (var x=0; x<callstack.length; x++){
console.log(callstack[x](), "should equal tools.functions");
}
How and when you infer the value of this really depends on when you have that object in scope. Presumably you are more likely to have that object in scope during the callstack creation phase, and perhaps not necessarily at the point where you wish to invoke the functions in the callstack. If that is the case, binding as early as possible (i.e. during the reduction to a unique callstack as demonstrated) seems like a sensible option.
In JavaScript, this is defined from the outside caller, so when you do:
callstack[x]()
You are bringing the window scope into the functions. If you want to bring in the tools.functions object, you need to do:
callstack[x].call(tools.functions);
http://jsfiddle.net/Yv4sM/
Related
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I am seeking help understanding why the way I am using anonymous functions are erroring in some circumstances.
In the snippet below I popuplate 2 arrays with functions which are invoked at a later stage.
var arr1 = [];
var arr2 = [];
// callback function
var func = function(i){
return function(){$("body").append(i);}
};
var i = 1;
while(i <= 5)
{
arr1.push(function(){$("body").append(i);});
arr2.push(func(i));
i++;
}
// invoke functions
$("body").append("Output from arr1 == ");
for(var c = 0; c < arr1.length; c++){ arr1[c](); }
$("body").append("<br> Output from arr2 == ");
for(var c = 0; c < arr1.length; c++){ arr2[c](); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Now, I think I understand why arr1 outputs 66666, because at the time of invocation, i == 6 and becuase it has not been stored as a param within that function at time of creation, i retains it's last known value?
What I really don't understand is why i recieve TypeError: arr2[c] is not a function When I change the callback function to:
var func = function(i){
$("body").append(i);
};
Why does this happen and is this the most appropriate / elegant way to achieve this functionality.
For the first part of the question, you are right, it will retain the latest known value. To avoid that, you need to use closure. For example:
(function(x) {
arr2.push(func(x));
})(i);
Closure can often be used as a "scope hack". In this case, it will only ensure that the injected value is the constant current value of i.
For the second part of the question, your confusion is probably caused by the fact that you insert the result of the function (i.e.: func(i)) instead of the function itself (func).
In the first scenario, you return an explicit function(){...} so your array will contain a function that you can call with operator "()".
In the second scenario, in which you return $(<...>).append(), it's not guaranteed anymore that your return value is a function. In that case, the result is "jQuery" (see: jQuery append) and not a function, hence the error is correct. You cannot use the value as a function.
One way out is:
arr2.push(func);
Then:
arr2[c](c);
Or probably this:
(function(x){
arr2[x](x);
})(c);
If needed, it can be helpful to always console.log what is populated inside your arrays before assuming it right. Since Javascript is not a typed language, you may go for a little while before suspecting anything wrong as it will seem work as intended.
Hope this helps!
I need to create wrapper functions around other functions. It is well known that arguments object is quite cranky and can't be passed to any function verbatim. Array creation in V8 is not cheap either. So the fastest code I could come up with is this:
function wrap (fun) {
// reuse the same array object for each call
var args = [];
var prevLen = 0;
return function () {
// do some wrappy things here
// only set args.length if it changed (unlikely)
var l = arguments.length;
if (l != prevLen) {
prevLen = args.length = l;
}
// copy the args and run the functon
for (var i = 0; i < l; i++) {
args[i] = arguments[i];
}
fun.apply(this, args);
};
}
var test = wrap(function (rec) {
document.write(arguments[1] + '<br />');
if (rec) test(false, 'something else');
document.write(arguments[1] + '<br />');
});
test(true, 'something');
This way I avoid creating or changing length of the array object unless really needed. The performance gain is quite serious.
The problem: I use the same array all over the place and it could change before the function call is finished (see example)
The question: is the array passed to .apply() copied to somewhere else in all JavaScript implementations? Is it guaranteed by the current EcmaScript spec that the fourth line of output will never ever be something else?
It works fine in all the browsers I checked, but I want to be future-proof here.
Is the array passed to .apply() copied to somewhere else, and is it guaranteed by the current EcmaScript spec?
Yes. The apply method does convert the array (or whatever you pass in) to a separate arguments list using CreateListFromArrayLike, which is then passed around and from which the arguments object for the call is created as well as the parameters are set.
According to the spec it is indeed supposed to be copied so the code seems to be safe.
Let argList be CreateListFromArrayLike(argArray).
Return Call(func, thisArg, argList).
I'm learning lots of javascript these days, and one of the things I'm not quite understanding is passing functions as parameters to other functions. I get the concept of doing such things, but I myself can't come up with any situations where this would be ideal.
My question is:
When do you want to have your javascript functions take another function as a parameter? Why not just assign a variable to that function's return value and pass that variable to the function like so:
// Why not do this
var foo = doStuff(params);
callerFunction(foo);
//instead of this
callerFunction(doStuff);
I'm confused as to why I would ever choose to do things as in my second example.
Why would you do this? What are some use cases?
Here's yet another example. Does some formatting operations on an array:
function pctFormatter(num) {
return num + '%';
}
function centsFormatter(num) {
return num + '.00';
}
function formatThisArray(array, formatter) {
var output = [];
for(var i = 0; i < array.length; i++) {
output.push( formatter(array[i]) );
}
return output;
}
formatThisArray([1,2,3], pctFormatter);// returns ['1%', '2%', '3%']
formatThisArray([1,2,3], centsFormatter);// returns ['1.00', '2.00', '3.00']
Handlers/listeners are a good example.
More generally, you can pass a function f as a parameter to function g when you don't know yet if g will need to call f, how many times it will need to call it, and/or with which parameters.
Examples:
sort algorithms: comparison function
regular expressions: replace function
callbacks (e.g. event handlers)
You'd do it when you don't have the params to pass, but the callerFunction() does.
A callback to an AJAX request is one use case.
function myCallback(response) {
// do something with the response
}
myAJAX('http://example.com/foo.json', myCallback)
This lets myAJAX to the work of making the request, and waiting for the response. Then it invokes myCallback and passes it the response when that response finally arrives.
// Why not do this
var foo = doStuff(params);
callerFunction(foo);
//instead of this
callerFunction(doStuff);
First example will run the function doStuff with params and the assign the result to foo. callerFunction will be called with parameter foo (which is now a result of dooStuff);
Second example will call callerFunction and pass doStuff as a parameter. The callerFunction might or might not call the doStuff.
Well, sometimes you don't know who the caller of a function will be until it's called - this precludes passing pre-calculated values.
A couple of examples that spring to mind are:
(a) setTimeout or setInterval - you want to call a specific function after a specified period, either one-shot, or repeatedly. If the function called returned a value that had a dependance on time, there are instances where you couldn't possibly pre-calculate the value - it needs to be done at the scheduled time. So, we tell the functions which of our own functions to call at the specified time.
(b) when loading (or at least attepmpting to) various resources. We can give the element a function that is to be executed when loading is successful, and another when it fails. You don't actually know when the effort to load a resource has finished until either of these two (user-supplied) functions are called. In the case of many resources, this is where you increment the counters that maintain the number of successful/failed load attempts.
(c) the NodeList returned by calls to getElementsByClass or getElementsByTagName. It's not an actual (javascript native) Array object. As such, you can't call the forEach method on it, like you can with an array. To get around this, I use the following helper function:
// getElementsByTagName, getElementsByClass - both return a NodeList
// it is accessed in the same way as an array - with the [] operators, but it's
// not an array object - this is a function that allows us to still iterate through it
// in much the same way.
function forEachNode(nodeList, func)
{
var i, n = nodeList.length;
for (i=0; i<n; i++)
{
func(nodeList[i], i, nodeList);
}
}
This allows me to get a list of nodes and then call some user-defined function on each of them. In use, it looks like this:
var allAnchors = document.getElementsByTagName('a');
forEachNode(allAnchors, showNodeTextVal);
function showNodeTextVal(curElem, curIndex, origList)
{
alert(curElem.innerText);
}
Or more simply:
var allAnchors = document.getElementsByTagName('a');
forEachNode(allAnchors, function(curElem){alert(curElem.innerText);} );
This is a much clearer, less error-prone situation than it would be if we didn't use this helper function. To achieve the same functionality, we'd need to code the following:
var nodeList = document.getElementsByTagName('a');
var i, n = nodeList.length;
for (i=0; i<n; i++)
{
alert(nodeList[i].innerText);
}
Most common case is handlers in JQuery:
function clickHandler(e){
// handle click on e.Target
}
$("#button").click(clickHandler);
$(function(){
// do ready state initialization
});
callerFunction(doStuff);
with this code you give a "pointer" of the function doStuff to the function callerFunction
you can use it like this:
function callerFunction(doStuff) {
var x = doStuff(...);
...;
}
you can so use the function in the function and not only the return value of doStuff.
greetings!
When do you want to have your javascript functions take another
function as a parameter?
It's useful for callbacks for example:
function add( a, b, callback ) {
callback( a, b );
return a + b;
}
function added( a, b ) {
alert('You just added two numbers: '+ a +' and '+ b);
}
alert( add( 1, 2, added ); // Will alert the message and then the result.
This a very simple example but it's very useful with asynchronous functions so you can run code after it has finished without interrupting the script.
You need to pass functions themselves, not return values, when you want to have your code really deal with functions as functions - code to execute. Consider this pseudo-code example:
function saveToLocalStorage(data) {...//saves to local storage}
function saveToServer(data) {...//saves via AJAX to server}
function saveToAmazonS3(data) {.../saves to Amazon S3 }
function multiSave(data, saverFunctions) {
saverFunctions.forEach(function (saverFunction) {
saverFunction(data);
});
}
multiSave({user: "tim"}, [saveToLocalStorage, saveToServer, saveToAmazonS3]);
In this case, I want the actual functions themselves to be passed around and for other code to later invoke them. When we do this, a function such as multiSave is called a higher-order function because it deals with other functions directly. Because of the way multiSave works, I can easily put some checkboxes in the UI next to local/server/S3 and allow the user to choose where their data goes in a way that would be less elegant if I was unable to pass functions around as arguments.
When you're passing a function as an argument, that argument is not the return value of that function, but it's the function itself, you can call it as much as you like, with any argument you like, or you can assign it to an event. You say you want some practical use cases, here's a short list of very common situations, all requiring a function to be passed as an argument.
Let's take a look at your average jQuery code, and count the number of times where a function is passed as an argument:
$(document).ready(function()//<-- 1
{
$('#foo').on('click',function()//2
{
});
$.each(something,function()//3
{});
//and so on
});
If you don't use jQuery, then try event delegation
document.body.addEventListener('click',function(e)
{
e = e || window.event
console.log('This function was passed as an argument to the addEventListener method');
},false);
Or even the simple Array.prototype.sort function (/method):
anArray.sort(function(a,b)
{
return (a > b ? 1 : -1);
});
Or in cases where you need to make an ajax call, instead of creating a new XMLHttpRequest object on the spot, you might want a single function that sets the xhr object up, and pass the url, data and onreadystatechange callback as arguments:
function makeXHR(url,data,callback)
{
try
{
var xhr = new XMLHttpRequest();
}
catch(e)
{
//etc...
}
xhr.onreadystatechange = callback;
}
makeXHR('some/url','foo=bar',function()
{
if (this.readyState === 4 && this.status === 200)
{
//do stuff
}
});
In all of these examples, I've created the functions in-line, of course referencing a function (by just passing its name) works just fine, too:
makeXHR('some/url','foo=bar',defaultXhrCallback);
These are just a few of thousands of use cases where you can/have to pass a function as an argument to another function
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 1 year ago.
I've never had to use callback functions before, so I may have made a completely stupid mistake. I think I somewhat understand the problem here, but not how to solve it.
My code (a bit simplified) is:
for (var i = 0; i < some_array.length; i++) {
var title = some_array[i];
$.getJSON('some.url/' + title, function(data) {
do_something_with_data(data, i);
}
Now as far as I understand, this anonymous function will only be called if getJSON() has received the data. But by this point, i does not have the value I would require. Or, as far as my observation goes, it has the last value it would have after the loop is done (shouldn't it be out of bounds?).
As a result, if the array had a size of 6, do_something_with_data() would be called five times with the value 5.
Now I thought, just pass i to the anonymous function
function(data, i) { }
but this does not seem to be possible. i is undefined now.
You need to understand what a closure is. In JavaScript, there are certain rules about the scope of each variable.
The scope for variables declared implicitly or with var is the nearest/current function (including "arrow functions"), or if not in a function, then the window or other global object appropriate for the execution context (e.g., in Node, global).
The scope for variables declared with let or const (in ES5 and up) is the nearest statement block { /* not an object, but any place that will take executable statements here */ }.
If any code can access a variable in the current scope or in any parent scope, this creates a closure around that variable, keeping the variable live and keeping any object referred to by the variable instantiated, so that these parent or inner functions or blocks can continue to refer to the variable and access the value.
Because the original variable is still active, if you later change the value of that variable anywhere in the code, then when code with a closure over that variable runs later it will have the updated/changed value, not the value when the function or scope was first created.
Now, before we address making the closure work right, note that declaring the title variable without let or const repeatedly in the loop doesn't work. var variables are hoisted into the nearest function's scope, and variables assigned without var that don't refer to any function scope get implicitly attached to the global scope, which is window in a browser. Before const and let existed, for loops in JavaScript had no scope, therefore variables declared within them are actually declared only once despite seeming to be (re)declared inside the loop. Declaring the variable outside the loop should help clarify for you why your code isn't working as you'd expect.
As is, when the callbacks run, because they have a closure over the same variable i, they are all affected when i increments and they will all use the current value of i when they run (which will as you discovered be incorrect, because the callbacks all run after the loop has completely finished creating them). Asynchronous code (such as the JSON call response) does not and cannot run until all synchronous code finishes executing--so the loop is guaranteed to complete before any callback is ever executed.
To get around this you need a new function to run that has its own scope so that in the callbacks declared inside of the loop, there is a new closure over each different value. You could do that with a separate function, or just use an invoked anonymous function in the callback parameter. Here's an example:
var title, i;
for (i = 0; i < some_array.length; i += 1) {
title = some_array[i];
$.getJSON(
'some.url/' + title,
(function(thisi) {
return function(data) {
do_something_with_data(data, thisi);
// Break the closure over `i` via the parameter `thisi`,
// which will hold the correct value from *invocation* time.
};
}(i)) // calling the function with the current value
);
}
For clarity I'll break it out into a separate function so you can see what's going on:
function createCallback(item) {
return function(data) {
do_something_with_data(data, item);
// This reference to the `item` parameter does create a closure on it.
// However, its scope means that no caller function can change its value.
// Thus, since we don't change `item` anywhere inside `createCallback`, it
// will have the value as it was at the time the createCallback function
// was invoked.
};
}
var title, i, l = some_array.length;
for (i = 0; i < l; i += 1) {
title = some_array[i];
$.getJSON('some.url/' + title, createCallback(i));
// Note how this parameter is not a *reference* to the createCallback function,
// but the *value that invoking createCallback() returns*, which is a function taking one `data` parameter.
}
Note: since your array apparently only has titles in it, you could consider using the title variable instead of i which requires you to go back to some_array. But either way works, you know what you want.
One potentially useful way to think about this that the callback-creating function (either the anonymous one or the createCallback one) in essence converts the value of the i variable into separate thisi variables, via each time introducing a new function with its own scope. Perhaps it could be said that "parameters break values out of closures".
Just be careful: this technique will not work on objects without copying them, since objects are reference types. Merely passing them as parameters will not yield something that cannot be changed after the fact. You can duplicate a street address all you like, but this doesn't create a new house. You must build a new house if you want an address that leads to something different.
You could create a closure using an immediate function (one that executes right away) that returns another function:
for (var i = 0; i < some_array.length; i++) {
var title = some_array[i];
$.getJSON('some.url/' + title, (function() {
var ii = i;
return function(data) {
do_something_with_data(data, ii);
};
})());
}
If you can modify the service at some.url, it would be much better if rather than making a separate HTTP request for each item in some_array, you simply passed every item in the array in a single HTTP request.
$.getJSON('some.url', { items: some_array }, callback);
Your array will be JSON serialized and POSTed to the server. Assuming some_array is an array of strings, the request will look like this:
POST some.url HTTP/1.1
...
{'items':['a','b','c', ... ]}
Your server script should then deserialize the JSON request from the request body and loop over each item in the items array, returning a JSON-serialized array of responses.
HTTP/1.1 200 OK
...
{'items':[{id:0, ... }, {id:1, ... }, ... ]}
(Or whatever data it is you're returning.) If your response items are in the same order as the request items, it is easy to piece things back together. In your success callback, simply match the item index with some_array's index. Putting it all together:
$.getJSON('some.url', { items: some_array }, function(data) {
for (var i = 0; i < data.items.length; i++) {
do_something_with_data(data.items[i], i);
}
});
By 'batching up' your requests into a single HTTP request like this, you'll significantly improve performance. Consider that if each network round-trip takes at least 200ms, with 5 items, you're looking at a minimum 1 second delay. By requesting them all at once, network delay stays a constant 200ms. (Obviously with larger requests, server script execution and network transfer times will come in to play, but performance will still be an order of a magnitude better than if you issue a separate HTTP request for each item.)
Create N closures and pass in the value of 'i' each time, like so:
var i, title;
for (i = 0; i < some_array.length; i++) {
title = some_array[i];
$.getJSON('some.url/' + title, (function(i_copy) {
return function(data) {
do_something_with_data(data, i_copy);
};
})(i));
}
I think some browsers have trouble with making multiple asynchronous calls at the same time, so you could make them one at a time:
var i;
function DoOne(data)
{
if (i >= 0)
do_something_with_data(data, i);
if (++i >= some_array.length)
return;
var title = some_array[i];
$.getJSON('some.url/' + title, DoOne);
}
// to start the chain:
i = -1;
DoOne(null);
I had exactly the same issue as the OP but solved it a different way. I replaced my JavaScript 'for' loop with a jQuery $.each which for each iteration calls a function which I think gets over the callback 'timing' issue. And I combined my external data arrays into a JavaScript object so that I could reference both the parameter I was passing on the JSON URL and the other field in the same element of that object. My object elements came out of a mySQL database table using PHP.
var persons = [
{ Location: 'MK6', Bio: 'System administrator' },
{ Location: 'LU4', Bio: 'Project officer' },
{ Location: 'B37', Bio: 'Renewable energy hardware installer' },
{ Location: 'S23', Bio: 'Associate lecturer and first hardware triallist' },
{ Location: 'EH12', Bio: 'Associate lecturer with a solar PV installation' }
];
function initMap() {
var map = new google.maps.Map(document.getElementById('map_canvas'), {
center: startLatLon,
minZoom: 5,
maxZoom: 11,
zoom: 5
});
$.each(persons, function(x, person) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=' + person.Location, null, function (data) {
var p = data.results[0].geometry.location;
var latlng = new google.maps.LatLng(p.lat, p.lng);
var image = 'images/solarenergy.png';
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image,
title: person.Bio
});
google.maps.event.addListener(marker, "click", function (e) {
document.getElementById('info').value = person.Bio;
});
});
});
}
I am completely perplexed. I have an object containing a global "hashed" array of numbers (in objectA) that is referred in a loop that combines the numbers into a new series (in objectB).
var objectB = objectA[arrActive[0]];
for (i=1; i<arrActive.length; i++) {
var _this = arrActive[i];
for (x=0; x<objectB.length; x++) {
objectB[x][1] += objectA[_this][x][1];
}
}
What's weird is that the values in objectA, the source array, are being incremented during the loop - but why? As far as I'm aware, I'm just reading from objectA to write to objectB!
This is frustrating because every time the function is called, the numbers are further inflated!
Working example on JSFiddle is here: http://jsfiddle.net/ZbWGH/ - have I completely misunderstood the += operator? I'm sure this is a simple issue to understand.
Thanks in advance for any help!
You're putting reference to the instance objectA['ONE'] in variable called objectB - any change in that variable will indeed change the actual value.
Instead you might be interested in getting clone or "clean copy" of the array into objectB and this way it won't change the original array.
Simple function that will do this is:
function CopyArray(arr) {
var clone = [];
for (var i = 0; i < arr.length; i++) {
var subArray = [];
for (var j = 0; j < arr[i].length; j++)
subArray.push(arr[i][j]);
clone.push(subArray);
}
return clone;
}
And to use it:
var objectB = CopyArray(objectA[arrActive[0]]);
Updated jsFiddle: http://jsfiddle.net/yahavbr/ZbWGH/1/
Further more A += B is like A = A + B, so you modify objectA.
Do you know C? References/pointers in C are a good way to understand komplex variables in Javascript. "Komplex" meaning everything that is not Number, String, Boolean - everything else is "Object". Variables for the komplex types (Objects) are indeed like pointers. If you know the concepts of "call by reference" and "call by value", in Javascript it's neither, sort of: If you give objects to functions the "pointer" itself is call by value, but the value is a reference to the object (really to the area on the heap where the object is stored, even though JS programmers don't handle heap like in C/C++ it still is where stuff is stored). Example:
function fn (a) {
//changing the argument itself does NOT change the original object
a = null;
//but changing its properties does:
a.foo = 42;
}
var o = { foo:1, bar:2 };
fn(o);
So now it should become clear why you have to clone an object if you want real "call by value". This implementation was chosen for JS because otherwise every single time a function is called with a non-primitive type the heap would have to be copied over, and 99% of the time that just is not necessary. The "true" spirit of functional programming would of course be pure call by value, here we see practical life (performance and memory usage) considerations intruding upon theory :)