"Uncaught Type" error with requestAnimationFrame - javascript

So I have written a working application (actually half of it) with requestAnimationFrame. Before the project gets too complex I'm rushing to rewrite it in an object-oriented style so we can implement plugins better (and also fix modules without changing the whole app). In fact the first version of the app was really messed up and made up from a lot of test code.
So I have the following:
Aventura.prototype.update = function() {
var av = this;
requestAnimationFrame(av.update);
/* ... frame code ... */
};
And I get "Uncaught TypeError: Type error " in the console log, right in the requestAnimationFrame line. I know my browser has a proper requestAnimationFrame implementation since I used the messed up version of my app perfectly well.
I've reached the conclusion that it raises an exception because I'm calling a method that is a member of the caller's own parent object (I know it's exactly the same method, but the problem clearly isn't on self-calling since that's what RAF is supposed to do). Any clues of what's wrong?

This has nothing to do with requestAnimationFrame. It is a basic JavaScript issue related to passing functions in general, and the meaning of this.
People tend to think that a function-valued property inside an object, such as myFn in the below
var myObj = {
myFn: function() {console.log(this);}
};
somehow has myObj "baked in" as this. Wrong. this is assigned only at the time the function is called. If I say myObj.myFn(), this becomes myObj, but I could just as easily say myObj.myFn.call(otherObj) to have this be something else.
This becomes important when passing functions around as parameters to setTimeout, promises, or requestAnimationFrame. Just passing myObj.myFn passes the function, but it has no associated this. requestAnimationFrame has no idea where this function came from and what this to call it with, so it calls it with a this of window, or null, or 0, or undefined, or who knows what. This causes the error.
The simplest way to fix the problem is to simply say
requestAnimationFrame(function() {av.update(); });
Now update is called with the correct this.
A more sophisticated, equivalent way, would be
requestAnimationFrame(av.update.bind(av));
Other note
I don't think the way you're passing the function itself to requestAnimationFrame is going to work well. You're essentially setting up a chain of recursive calls, and eventually the stack will overflow. You need to separate the logic to be executed on the requestAnimationFrame callback from the logic to request the frame.

I've ended up finding the answer on another question here. I don't think it classifies as a duplicate though, since both questions were asked in different ways and someone could find one but not the other question (I myself seeked for a similar problem all over the web and didn't ever run into this potential duplicate).
How to call requestAnimFrame on an object method?

Related

When creating a function to run only one time, should the redefinition happen before or after the function?

I want a function to only run one time. I found this question here on SO and the highest voted examples redefine the function and then execute the code that is supposed to run once. I'm sure there is a good reason for doing that instead of running the code and then redefining the function but I can't figure out what that would be. My first instinct would be to only redefine the function after the code is run since that seems "safer" because the code would have to have run before being redefined.
Can someone explain why convention seems to be to redefine first?
Basically if you want to avoid that the function is "called" twice, disabling the function immediately after the first call is the safest thing to do. When nothing else can happen between the call and the disabler, then nothing unexpected can happen either. If you were to run the code that should be executed only once first, various things might happen:
the code calls the function recursively, or through a callback - you should consider reentrancy
the code does throw an exception
the code returns early
In any of these cases, and possibly more, the disabling code is not reached and a second call could be made.
Notice also that replacing the function is not enough. A caller could easily have created an alias variable that still holds the original function, unaffected by setting some other variable to a noop function. You always need to combine this solution with the "static boolean variable" approach from the accepted answer, unless you control the calling code and know what it does.
Looks like the main reason is for multi-threaded languages. If a function is supposed to run only once and it gets called a second time before the first instance is complete, that would result in being called more than once. Redefining it first means that the function can't run twice.

Is this recursion or not

function x(){
window.setTimeout(function(){
foo();
if(notDone()){
x();
};
},1000);
}
My concern being unbounded stack growth. I think this is not recursion since the x() call in the timer results in a brand new set of stack frames based on a new dispatch in the JS engine.
But reading the code as an old-fashioned non JS guy it makes me feel uneasy
One extra side question, what happens if I scheduled something (based on math rather than a literal) that resulted in no delay. Would that execute in place or would it be in immediately executed async, or is that implementation defined
It's not - I call it "pseudo-recursion".
The rationale is that it kind of looks like recursion, except that the function always correctly terminates immediately, hence unwinding the stack. It's then the JS event loop that triggers the next invocation.
It is recusive in a sense that it is a function that calls itself but I believe you are right about the stack trace being gone. Under normal execution the stack will just show that it was invoked by setTimeout. The chrome debugger for example will allow you to keep stack traces on async execution, I am not sure how they are doing it but the engine can keep track of the stack somehow.
No matter how the literal is calculated the execution will still be async.
setTimeout(function(){console.log('timeout');}, 0);console.log('executing');
will output:
executing
undefined
timeout
One extra side question, what happens if I scheduled something (based on math rather than a literal) that resulted in no delay. Would that execute in place or would it be in immediately executed async, or is that implementation defined
Still asynchronous. It's just that the timer will be processed immediately once the function returns and the JavaScript engine can process events on the event loop.
Recursion has many different definitions, but if we define it as the willful (as opposed to bug-induced) use of a function that calls itself repeatedly in order to solve a programming problem (which seems to be a common one in a Javascript context), it absolutely is.
The real question is whether or not this could crash the browser. The answer is no in my experience...at least not on Firefox or Chrome. Whether good practice or not, what you've got there is a pretty common Javascript pattern, used in a lot of semi-real-time web applications. Notably, Twitter used to do something very similar to provide users with semi-real-time feed updates (I doubt they still do it now that they're using a Node server).
Also, out of curiously I ran your script with the schedule reset to run every 50ms, and have experienced no slowdowns.

jQuery Event Callback Speed: Anonymous vs. Named Functions

This is kind of a random question, but I was wondering why a named callback was performing worse, for a click event, relative to an anonymous function.
Here is the link to the JSPerf tests I ran in Firefox and Chrome on Mac.
I guess my assumption was that named callbacks would always perform better. For instance, when using .each the named callback is slightly faster.
Thanks for your time!
Edit I edited the .each JSPerf test because (a) I wasn't testing what I meant and (b) I'm trying to mimic events more so.
Edit 2 My test setup was incorrect from the start as #Esailija points out below. This question is somewhat pointless but at least it might help someone with JSPerf testing.
The jsperf is broken because you accumulate event handlers across test boundaries. In other wrods, whatever test is run first will be the "fastest".
And the whole premise of the test is ridiculous, there is no difference between a function that has a name and a function that doesn't have a name if everything else is equal. You will only see a difference when you are setting up jsperf incorrectly. When you constantly get equal results for them then you know that you set it up correctly - but you would know this already from common sense :)
The anonymous function is passed as an argument, so to resolve its reference, the scope chain does not reach all the way back to the parent function that created it - it only exists as an argument. On the other hand, to resolve the reference to the named function, the scope chain is followed all the way back to the parent function closure where the named function was created.
Edit:
I tried to prove this, but it seems as if the anonymous function does not actually get resolved faster - http://jsperf.com/scope-chain-anonymous-function
Edit: If you call a.off(); to remove any event handlers, the named function will be just as fast or faster than resolving the anonymous function.
http://jsperf.com/jquery-events-anonymous-vs-named-callbacks/2
http://jsperf.com/jquery-event-callback-nested/2

What are the benefits to using anonymous functions instead of named functions for callbacks and parameters in JavaScript event code?

I'm new-ish to JavaScript. I understand many of the concepts of the language, I've been reading up on the prototype inheritance model, and I'm whetting my whistle with more and more interactive front-end stuff. It's an interesting language, but I'm always a bit turned off by the callback spaghetti that is typical of many non-trivial interaction models.
Something that has always seemed strange to me is that in spite of the readability nightmare that is a nest of JavaScript nested callbacks, the one thing that I very rarely see in many examples and tutorials is the use of predefined named functions as callback arguments. I'm a Java programmer by day, and discarding the stereotypical jabs about Enterprise-y names for units of code one of the things I've come to enjoy about working in a language with a strong selection of featureful IDE's is that using meaningful, if long, names can make the intent and meaning of code much clearer without making it more difficult to actually be productive. So why not use the same approach when writing JavaScript code?
Giving it thought, I can come up with arguments that are both for and against this idea, but my naivety and newness to the language impairs me from reaching any conclusions as to why this would be good at a technical level.
Pros:
Flexibility. An asynchronous function with a callback parameter could be reached by one of many different code paths and it could be harried to have to write a named function to account for every single possible edge case.
Speed. It plays heavily in to the hacker mentality. Bolt things on to it until it works.
Everyone else is doing it
Smaller file sizes, even if trivially so, but every bit counts on the web.
Simpler AST? I would assume that anonymous functions are generated at runtime and so the JIT won't muck about with mapping the name to instructions, but I'm just guessing at this point.
Quicker dispatching? Not sure about this one either. Guessing again.
Cons:
It's hideous and unreadable
It adds to the confusion when you're nested nuts deep in a swamp of callbacks (which, to be fair, probably means you're writing poorly constructed code to begin with, but it's quite common).
For someone without a functional background it can be a bizarre concept to grok
With so many modern browsers showing the ability to execute JavaScript code much faster than before, I'm failing to see how any trivial sort of performance gain one might get out using anonymous callbacks would be a necessity. It seems that, if you are in a situation where using a named function is feasible (predictable behavior and path of execution) then there would be no reason not to.
So are there any technical reasons or gotchas that I'm not aware of that makes this practice so commonplace for a reason?
I use anonymous functions for three reasons:
If no name is needed because the function is only ever called in one place, then why add a name to whatever namespace you're in.
Anonymous functions are declared inline and inline functions have advantages in that they can access variables in the parent scopes. Yes, you can put a name on an anonymous function, but that's usually pointless if it's declared inline. So inline has a significant advantage and if you're doing inline, there's little reason to put a name on it.
The code seems more self-contained and readable when handlers are defined right inside the code that's calling them. You can read the code in almost sequential fashion rather than having to go find the function with that name.
I do try to avoid deep nesting of anonymous functions because that can be hairy to understand and read. Usually when that happens, there's a better way to structure the code (sometimes with a loop, sometimes with a data table, etc...) and named functions isn't usually the solution there either.
I guess I'd add that if a callback starts to get more than about 15-20 lines long and it doesn't need direct access to variables in the parent scope, I would be tempted to give it a name and break it out into it's own named function declared elsewhere. There is definitely a readability point here where a non-trivial function that gets long is just more maintainable if it's put in its own named unit. But, most callbacks I end up with are not that long and I find it more readable to keep them inline.
I prefer named functions myself, but for me it comes down to one question:
Will I use this function anywhere else?
If the answer is yes, I name/define it. If not, pass it as an anonymous function.
If you only use it once, it doesn't make sense to crowd the global namespace with it. In today's complex front-ends, the number of named functions that could have been anonymous grows quickly (easily over 1000 on really intricate designs), resulting in (relatively) large performance gains by preferring anonymous functions.
However, code maintainability is also extremely important. Each situation is different. If you're not writing a lot of these functions to begin with, there's no harm in doing it either way. It's really up to your preference.
Another note about names. Getting in the habit of defining long names will really hurt your file size. Take the following example.
Assume both of these functions do the same thing:
function addTimes(time1, time2)
{
// return time1 + time2;
}
function addTwoTimesIn24HourFormat(time1, time2)
{
// return time1 + time2;
}
The second tells you exactly what it does in the name. The first is more ambiguous. However, there are 17 characters of difference in the name. Say the function is called 8 times throughout the code, that's 153 extra bytes your code didn't need to have. Not colossal, but if it's a habit, extrapolating that to 10s or even 100s of functions will easily mean a few KB of difference in the download.
Again however, maintainability needs to be weighed against the benefits of performance. This is the pain of dealing with a scripted language.
A bit late to the party, but some not yet mentioned aspects to functions, anonymous or otherwise...
Anon funcs are not easily referred to in humanoid conversations about code, amongst a team. E.g., "Joe, could you explain what the algorithm does, within that function. ... Which one? The 17th anonymous function within the fooApp function. ... No, not that one! The 17th one!"
Anon funcs are anonymous to the debugger as well. (duh!) Therefore, the debugger stack trace will generally just show a question mark or similar, making it less useful when you have set multiple breakpoints. You hit the breakpoint, but find yourself scrolling the debug window up/down to figure out where the hell you are in your program, because hey, question mark function just doesn't do it!
Concerns about polluting the global namespace are valid, but easily remedied by naming your functions as nodes within your own root object, like "myFooApp.happyFunc = function ( ... ) { ... }; ".
Functions that are available in the global namespace, or as nodes in your root object like above, can be invoked from the debugger directly, during development and debug. E.g., at the console command line, do "myFooApp.happyFunc(42)". This is an extremely powerful ability that does not exist (natively) in compiled programming languages. Try that with an anon func.
Anon funcs can be made more readable by assigning them to a var, and then passing the var as the callback (instead of inlining). E.g.:
var funky = function ( ... ) { ... };
jQuery('#otis').click(funky);
Using the above approach, you could potentially group several anon funcs at the top of the parental func, then below that, the meat of sequential statements becomes much tighter grouped, and easier to read.
Anonymous functions are useful because they help you control which functions are exposed.
More Detail: If there is no name, you can't reassign it or tamper with it anywhere but the exact place it was created. A good rule of thumb is, if you don't need to re-use this function anywhere, it's a good idea to consider if an anonymous function would be better to prevent getting tampered with anywhere.
Example:
If you're working on a big project with a lot of people, what if you have a function inside of a bigger function and you name it something? That means anyone working with you and also editing code in the bigger function can do stuff to that smaller function at any time. What if you named it "add" for instance, and someone reassigned "add" to a number instead inside the same scope? Then the whole thing breaks!
PS -I know this is a very old post, but there is a much simpler answer to this question and I wish someone had put it this way when I was looking for the answer myself as a beginner- I hope you're ok with reviving an old thread!
Its more readable using named functions and they are also capable of self-referencing as in the example below.
(function recursion(iteration){
if (iteration > 0) {
console.log(iteration);
recursion(--iteration);
} else {
console.log('done');
}
})(20);
console.log('recursion defined? ' + (typeof recursion === 'function'));
http://jsfiddle.net/Yq2WD/
This is nice when you want to have an immediately invoked function that references itself but does not add to the global namespace. It's still readable but not polluting. Have your cake and eat it to.
Hi, my name is Jason OR hi, my name is ???? you pick.
Well, just to be clear for the sake of my arguments, the following are all anonymous functions/function expressions in my book:
var x = function(){ alert('hi'); },
indexOfHandyMethods = {
hi: function(){ alert('hi'); },
high: function(){
buyPotatoChips();
playBobMarley();
}
};
someObject.someEventListenerHandlerAssigner( function(e){
if(e.doIt === true){ doStuff(e.someId); }
} );
(function namedButAnon(){ alert('name visible internally only'); })()
Pros:
It can reduce a bit of cruft, particularly in recursive functions (where you could (should actually since arguments.callee is deprecated) still use a named reference per the last example internally), and makes it clear the function only ever fires in this one place.
Code legibility win: in the example of the object literal with anon funcs assigned as methods, it would be silly to add more places to hunt and peck for logic in your code when the whole point of that object literal is to plop some related functionality in the same conveniently referenced spot. When declaring public methods in a constructor, however, I do tend to define labeled functions inline and then assign as references of this.sameFuncName. It lets me use the same methods internally without the 'this.' cruft and makes order of definition a non-concern when they call each other.
Useful for avoiding needless global namespace pollution - internal namespaces, however, shouldn't ever be that broadly filled or handled by multiple teams simultaneously so that argument seems a bit silly to me.
I agree with the inline callbacks when setting short event handlers. It's silly to have to hunt for a 1-5 line function, especially since with JS and function hoisting, the definitions could end up anywhere, not even within the same file. This could happen by accident without breaking anything and no, you don't always have control of that stuff. Events always result in a callback function being fired. There's no reason to add more links to the chain of names you need to scan through just to reverse engineer simple event-handlers in a large codebase and the stack trace concern can be addressed by abstracting event triggers themselves into methods that log useful info when debug mode is on and fire the triggers. I'm actually starting to build entire interfaces this way.
Useful when you WANT the order of function definition to matter. Sometimes you want to be certain a default function is what you think it is until a certain point in the code where it's okay to redefine it. Or you want breakage to be more obvious when dependencies get shuffled.
Cons:
Anon functions can't take advantage of function hoisting. This is a major difference. I tend to take heavy advantage of hoisting to define my own explicitly named funcs and object constructors towards the bottom and get to the object definition and main-loop type stuff right up at the top. I find it makes the code easier to read when you name your vars well and get a broad view of what's going on before ctrl-Fing for details only when they matter to you. Hoisting can also be a huge benefit in heavily event-driven interfaces where imposing a strict order of what's available when can bite you in the butt. Hoisting has its own caveats (like circular reference potential) but it is a very useful tool for organizing and making code legible when used right.
Legibility/Debug. Absolutely they get used way too heavily at times and it can make debug and code legibility a hassle. Codebases that rely heavily on JQ, for instance, can be a serious PITA to read and debug if you don't encapsulate the near-inevitable anon-heavy and massively overloaded args of the $ soup in a sensible way. JQuery's hover method for instance, is a classic example of over-use of anon funcs when you drop two anon funcs into it, since it's easy for a first-timer to assume it's a standard event listener assignment method rather than one method overloaded to assign handlers for one or two events. $(this).hover(onMouseOver, onMouseOut) is a lot more clear than two anon funcs.

javascript profile in Firefox

(I know some people already asked questions about js profile, but that's not what I need if I understand them correctly.)
I'd like to trace the execution of javascript to collect the information of 1) which function is invoked, 2) the time when the function is invoked, and 3) the execution time of the function.
I want to collect the information online (on deployed code) but not in-house. So, the trade-off has to be light. Also, I don't want to manually add a line before and after where a function is invoked. However, it would be great if there's a way that can dynamically instrument the code.
Thanks in advance!
I don't think that there is any system whereby JavaScript will automatically track the time a function starts and the time a function stops. That is likely something you will have to add yourself. If this is what you need, you may want to consider using PHP to serve up your JavaScript and use a regular expression to find the beginnings and ends of each function with a regex or something like that.
Your RegExp might look like this (completely untested, so you'll have to experiment):
/function [A-Za-z_$][A-Za-z0-9_$]*{(.*?)}/i
Once you have access to the inside of the function, you could replace that value with the function to track its beginning and end wrapped around the original function definition.
This has the benefit of doing exactly what you want, without worrying about modifying how your js code functions. It is then something the server will handle entirely.
Either that or, instead of calling the function directly, use a wrapper function:
function wrapFunction( func, context, argList )
{
// Replace with however you are storing this.
console.log( new Date().getTime() );
func.apply( context, argList );
console.log( new Date().getTime() );
}
This has the benefit of being a lot cleaner than having the server update your JS for you. Unfortunately, it also means having to re-write the JS manually.
My recommendation would be to simply adapt a logging syntax and use that. Most loggers will output a timestamp, a context, a level, and a specific message. If you simply call the logger at the beginning and end of the function, it will do exactly what you're looking for. Further, since many are configurable, you would be able to have it display to the JS console in Firefox, send information to the server, or completely disabled if you so chose.
There are a list of JS loggers here:
JavaScript loggers
This would unfortunately require you to manually update everything, but it seems like the simplest way to get 90% of what you're looking for out of the box.
Perhaps the profiler in FireBug can help you track down slow functions.
Here's a video detailing the profiling options. (Index: 3:20).
console.profile([title])
//also see
console.trace()
http://getfirebug.com/wiki/index.php/Console_API

Categories

Resources