Why won't my timer increment the number? - javascript

I recently learned javascript. I was experimenting with it. Now, I tried to make a simple timer. Here is the code:
<html>
<head>
<script type="text/javascript">
function start(obj)
{
var t = setTimeout("increment(obj)", 1000);
}
function increment(obj)
{
obj.innerHTML = parseInt(obj.innerHTML) + 1;
start(obj);
}
</script>
</head>
<body>
<p onclick="start(this)">0</p>
</body>
</html>
The contents of the <p></p> should be incremented by 1 every second. Does anyone know why this doesn't work?

Because the string you pass into setTimeout is evaluated at global scope, not the scope within the function, and so doesn't refer to your obj object.
You should never pass strings to setTimeout. Instead, pass it a function reference:
function start(obj)
{
var t = setTimeout(function() {
increment(obj);
}, 1000);
}
function increment(obj)
{
obj.innerHTML = parseInt(obj.innerHTML) + 1;
start(obj);
}
The function we're passing to setTimeout is a closure, which means it has an enduring reference to the items in scope where it's defined. So a second later when the timer mechanism calls it, it still has access to the obj argument of your start function even though the start function has long since returned. More here: Closures are not complicated

The issue (or at least, the first that I see) is that you are passing the string "increment(obj)" to the setTimeout() method, but obj is only defined inside of your start() method. The string that you pass isn't actually evaluated until the timeout triggers, at which point no obj variable is in scope.
There are a few different ways around this. One is to pass a closure to setTimeout() instead of a JavaScript string, like:
function start(obj) {
var nextIncrement = function() {
increment(obj);
};
var t = setTimeout(nextIncrement, 1000);
}
Another (though less preferable) option is to promote obj to the global scope, like:
function start(obj) {
window.obj = obj;
var t = setTimeout("increment(obj)", 1000);
}
In general, however, you should avoid passing a string to setTimeout (and you should also avoid placing things in the global scope unnecessarily). As you have seen, it can cause issues with scope resolution, and for any non-trivial operation it also makes you code much less maintainable. Always prefer passing a function closure when possible.
Also, the following line of code is probably not doing exactly what you expect:
parseInt(obj.innerHTML)
You should always provide the radix argument to parseInt, to avoid errors with values such as 011 (which is 9, rather than 11, because it is evaluated in base-8 due to the leading 0). You can avoid these quirks by simply doing:
parseInt(obj.innerHTML, 10)
...to force a base-10 parse.
Anyways, working example here: http://jsfiddle.net/dSLZG/1

The problem is with this line of code:
var t = setTimeout("increment(obj)", 1000);
obj is an identifier in the functions scope -- it is only accessible within the start function. When you pass a string to setTimeout, it is evaluated in the global scope. This means that the obj variable is not available, so nothing is incremented.
You should pass a function object instead, as this will create a closure and your variable will be accessible:
function start(obj)
{
setTimeout(function() {
increment(obj);
}, 1000);
}
Note that I have removed the unnecessary var t =, because you're not doing anything with the timer identifier.

I've copied your code over to jsFidle and added a working example. See sample code.
The problem in your original version is that your variable obj is not defined in the global context. Whenever you pass strings to setTimeout you'll end up having the string evaluated in the global context (where obj is not a variable).
What you should do instead is never pass a string to setTimeout but a function object. This function object holds references to all variables that are set where the function object was defined.
So, because the function object passed to setTimeout in start2 is defined within start2 it has access to all variables and parameters of start2. Your variable obj is one of those and thus accessible within the function object as soon as it is executed by setTimeout.

Related

Closure of function defined as an argument

Disclaimer: This question is purely curiosity driven and has to do a lot with how the javascript works.
I understand why the following code works. Due to closures, foo has access to the scope where a resides. This makes sense.
var a = 10
var foo = function(){
console.log(a);
}
setTimeout(foo,1000)
However, i wonder why the following also works (explained right after).
var a = 10
setTimeout(function(){
console.log(a);
},1000)
The function is defined in the argument of the function receiving it and essentially was never a closure to the scope that contains a. We know that when a function receives an argument, it creates a local variable for that argument so for example
var outerVar="5"
var bar = function(a){
//implicitly, var a = outerVar happens here
console.log(a)
}
bar(something);
So following that logic, the function passed to setTimeout couldnt have access to a and yet it does.
Im suspecting that when a function is defined in the argument space what happens is, it realy is defined before being assigned as an argument but have no proof of that. Any pointers highly appreciated.
Thanks a bunch.
It's not exactly closure, but it's close.
Strictly speaking, closure is when a variable's scope ends, but is still enclosed in an inner function that still lives on:
function createTimer() {
let counter = 0;
return function() {
return counter++;
}
}
const timer = createTimer(); // function() { ... }
console.log(timer(), timer(), timer()); // 0, 1, 2
The function in which counter is defined has returned, the scope ended, and under normal circumstances, counter should have died and garbage collected. But the inner function returned from createTimer() still has a reference to it, from the enclosed scope, that is a closure.
In JavaScript, every function has access to all of the scopes of all of its ancestors, this is what you're seeing here.
The function passed to setTimeout() has access to a because a is defined in the scope around it.
When you look at a javascript code and see how it works, the best way according to me is first understand the javascript engine how it works.
First it traverses the code and assigns all the variables to the scope and further more in the second trace it assigns the values based on the scopes.
So in your first code,
The engine first traverses and assigns
var a to global scope,
var foo as global scope,
Then when setTimeout runs it calls foo function and logs the value of a as that of the global a as it doesnt have any local “a” so checks the lexical scoping.
In your second code,
Var a is again global scoped
and no other declaration this time.
In second traverse it assigns the value 10 to a and interprets the settimeout and prints the value
In your third code,
Same as the second one except the fact that instead what “foo” was giving to the settimeout function, you wrote your callback function then n there itself.
By the time l it executed the setTimeout,
Each of your codes have the value for “a” in the global scope that they are accessing.

Execute private function inside the class by its name (string)

At the moment I have simple JavaScript class like this:
function MyClass() {
// ... some code ...
this.Create = function() {
funcName = 'myTestFunc()';
cTimer = setTimeout(funcName, 1000);
}
// ... more code ...
var myTestFunc = function() {
alert ('everything\'s OK!');
}
// ... more code ...
}
and to test it I'm using this code:
x = new MyClass();
x.Create();
I have some troubles to execute this function by it's name. If I put just eval(funcName); instead of setTimeout call it works fine but can't figure out why it doesn't work this way.
Course, this is part of more complex code but rest of code is irrelevant to this problem.
My question is obvious - How to execute function by its name set as setTimeout function's argument? Is it possible?
Note: Making this function public (this.myTestFunc = ...) isn't an option!
Update:
funcName = "myTestFunc()"; is just an example. In real code it looks like funcName = getRandomEffectFunctionName();! It's just a random value.
Referring to the update:
Instead of setting:
var funcName = "getRandomEffectFunctionNeme()";
Thus, setting a reference to the function's name you should do
var funcRef = getRandomEffectFunctionNeme;
And set a reference to the function itself . Not only this avoids the issues setTimeout with strings has*. It also solves your closure issue since your code is structured in such a way the timeout has access to the function itself.
In your case, let's assume you have some functions that are filters, for example lowPass highPass and blur. In that case, instead of choosing a function name we would be choosing a function.
First, we store these functions in an array:
var filters = [lowPass,highPass,blur];
In JavaScript, functions are first-class objects, you can pass them around just like other objects.
Next, we'll get a random number
var chosen = Math.floor(Math.random()*3);//get a random number between 0 and 2
Finally, we'll choose the filter and invoke it
var filter = filters[chosen];
setTimeout(filter,1000);
( * just try debugging it, it basically invokes the compiler whenever ran and is painfully slow)
You just pass a function to setTimeout as a parameter, rather then a string, setTimeout(myTestFunc,1000) .
When calling Create it would have access to it anyway because they are in the same closure.
NOTE: This solution is only applicable if you can not pass the function name as a function reference, for example if you're integrating with code that is outside your control. Generally, when possible, you should pass a function reference since in JavaScript, all functions are objects.
Assuming that the timeout and the function are in the same closure your code is pretty close. The problem is that your eval call executes in the global context because it is in a timer. This means they are no longer in the same lexical scope.
You can however, grab a reference to the function by clever use of eval which you can later call in the setTimeout invocation.
var F=eval(funcName);// gain a reference to the function given the function's name
cTimer = setTimeout(F, 1000);
If you're using AIR or don't trust the functionName string you can do the following:
function Test(){
var functionContainer={
t:function(){
console.log("it's t");
}
};
this.callT=function(functionName){
var F=functionContainer[functionName];
console.log("F is:",F);
setTimeout(F,500);
}
}
(new Test()).call("t");
This is preferable since you are invoking setTimeout with a function's name and not a string. In general, using setTimeout with a string can have issues, it's hard to debug or maintain.

setTimeout giving arguments to function from another function

Got a problem, don't know how can I give to ClickSimClick function arguments exposed by ClickSimMove func (it returns array with 2 values).
Code below says that crd is undefined on setTimeout.
var crd = plugin().ClickSimMove();
setTimeout("plugin().ClickSimClick(crd[0], crd[1])", 1000);
Pass a function, not a string:
var crd = plugin().ClickSimMove();
setTimeout(function() {
plugin().ClickSimClick(crd[0], crd[1]);
}, 1000);
When you pass a string, it's evaluated as it would be with eval in the global scope, losing all access to local variables. An anonymous function lets you reference any variable in scope.
var crd = plugin().ClickSimMove();
setTimeout(function(){
plugin().ClickSimClick(crd[0], crd[1]);
}, 1e3);
When at all possible, avoid sending strings to setTimeout/setInterval--use an anonymous function instead. Especially if you find yourself concatenating variables to make that string, you can run in to trouble very quickly with some sort of injection or malformed component.

Why is this function wrapped in parentheses, followed by parentheses? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 9 years ago.
I see this all the time in javascript sources but i've never really found out the real reason this construct is used. Why is this needed?
(function() {
//stuff
})();
Why is this written like this? Why not just use stuff by itself and not in a function?
EDIT: i know this is defining an anonymous function and then calling it, but why?
This defines a function closure
This is used to create a function closure with private functionality and variables that aren't globally visible.
Consider the following code:
(function(){
var test = true;
})();
variable test is not visible anywhere else but within the function closure where it's defined.
What is a closure anyway?
Function closures make it possible for various scripts not to interfere with each other even though they define similarly named variables or private functions. Those privates are visible and accessible only within closure itself and not outside of it.
Check this code and read comments along with it:
// public part
var publicVar = 111;
var publicFunc = function(value) { alert(value); };
var publicObject = {
// no functions whatsoever
};
// closure part
(function(pubObj){
// private variables and functions
var closureVar = 222;
var closureFunc = function(value){
// call public func
publicFunc(value);
// alert private variable
alert(closureVar);
};
// add function to public object that accesses private functionality
pubObj.alertValues = closureFunc;
// mind the missing "var" which makes it a public variable
anotherPublic = 333;
})(publicObject);
// alert 111 & alert 222
publicObject.alertValues(publicVar);
// try to access varaibles
alert(publicVar); // alert 111
alert(anotherPublic); // alert 333
alert(typeof(closureVar)); // alert "undefined"
Here's a JSFiddle running code that displays data as indicated by comments in the upper code.
What it actually does?
As you already know this
creates a function:
function() { ... }
and immediately executes it:
(func)();
this function may or may not accept additional parameters.
jQuery plugins are usually defined this way, by defining a function with one parameter that plugin manipulates within:
(function(paramName){ ... })(jQuery);
But the main idea is still the same: define a function closure with private definitions that can't directly be used outside of it.
That construct is known as a self-executing anonymous function, which is actually not a very good name for it, here is what happens (and why the name is not a good one). This:
function abc() {
//stuff
}
Defines a function called abc, if we wanted an anonymous function (which is a very common pattern in javascript), it would be something along the lines of:
function() {
//stuff
}
But, if you have this you either need to associate it with a variable so you can call it (which would make it not-so-anonymous) or you need to execute it straight away. We can try to execute it straight away by doing this:
function() {
//stuff
}();
But this won't work as it will give you a syntax error. The reason you get a syntax error is as follows. When you create a function with a name (such as abc above), that name becomes a reference to a function expression, you can then execute the expression by putting () after the name e.g.: abc(). The act of declaring a function does not create an expression, the function declaration is infact a statement rather than an expression. Essentially, expression are executable and statements are not (as you may have guessed). So in order to execute an anonymous function you need to tell the parser that it is an expression rather than a statement. One way of doing this (not the only way, but it has become convention), is to wrap your anonymous function in a set of () and so you get your construct:
(function() {
//stuff
})();
An anonymous function which is immediately executed (you can see how the name of the construct is a little off since it's not really an anonymous function that executes itself but is rather an anonymous function that is executed straight away).
Ok, so why is all this useful, one reason is the fact that it lets you stop your code from polluting the global namespace. Because functions in javascript have their own scope any variable inside a function is not visible globally, so if we could somehow write all our code inside a function the global scope would be safe, well our self-executing anonymous function allows us to do just that. Let me borrow an example from John Resig's old book:
// Create a new anonymous function, to use as a wrapper
(function(){
// The variable that would, normally, be global
var msg = "Thanks for visiting!";
// Binding a new function to a global object
window.onunload = function(){
// Which uses the 'hidden' variable
alert( msg );
};
// Close off the anonymous function and execute it
})();
All our variables and functions are written within our self-executing anonymous function, our code is executed in the first place because it is inside a self-executing anonymous function. And due to the fact that javascript allows closures, i.e. essentially allows functions to access variables that are defined in an outer function, we can pretty much write whatever code we like inside the self-executing anonymous function and everything will still work as expected.
But wait there is still more :). This construct allows us to solve a problem that sometimes occurs when using closures in javascript. I will once again let John Resig explain, I quote:
Remember that closures allow you to reference variables that exist
within the parent function. However, it does not provide the value of
the variable at the time it is created; it provides the last value of
the variable within the parent function. The most common issue under
which you’ll see this occur is during a for loop. There is one
variable being used as the iterator (e.g., i). Inside of the for loop,
new functions are being created that utilize the closure to reference
the iterator again. The problem is that by the time the new closured
functions are called, they will reference the last value of the
iterator (i.e., the last position in an array), not the value that you
would expect. Listing 2-16 shows an example of using anonymous
functions to induce scope, to create an instance where expected
closure is possible.
// An element with an ID of main
var obj = document.getElementById("main");
// An array of items to bind to
var items = [ "click", "keypress" ];
// Iterate through each of the items
for ( var i = 0; i < items.length; i++ ) {
// Use a self-executed anonymous function to induce scope
(function(){
// Remember the value within this scope
var item = items[i];
// Bind a function to the element
obj[ "on" + item ] = function() {
// item refers to a parent variable that has been successfully
// scoped within the context of this for loop
alert( "Thanks for your " + item );
};
})();
}
Essentially what all of that means is this, people often write naive javascript code like this (this is the naive version of the loop from above):
for ( var i = 0; i < items.length; i++ ) {
var item = items[i];
// Bind a function to the elment
obj[ "on" + item ] = function() {
alert( "Thanks for your " + items[i] );
};
}
The functions we create within the loop are closures, but unfortunately they will lock in the last value of i from the enclosing scope (in this case it will probably be 2 which is gonna cause trouble). What we likely want is for each function we create within the loop to lock in the value of i at the time we create it. This is where our self-executing anonymous function comes in, here is a similar but perhaps easier to understand way of rewriting that loop:
for ( var i = 0; i < items.length; i++ ) {
(function(index){
obj[ "on" + item ] = function() {
alert( "Thanks for your " + items[index] );
};
})(i);
}
Because we invoke our anonymous function on every iteration, the parameter we pass in is locked in to the value it was at the time it was passed in, so all the functions we create within the loop will work as expected.
There you go, two good reasons to use the self-executing anonymous function construct and why it actually works in the first place.
It's used to define an anonymous function and then call it. I haven't tried but my best guess for why there are parens around the block is because JavaScript needs them to understand the function call.
It's useful if you want to define a one-off function in place and then immediately call it. The difference between using the anonymous function and just writing the code out is scope. All the variables in the anonymous function will go out of scope when the function's over with (unless the vars are told otherwise, of course). This can be used to keep the global or enclosing namespace clean, to use less memory long-term, or to get some "privacy".
It is an "anonymous self executing function" or "immediately-invoked-function-expression". Nice explanation from Ben Alman here.
I use the pattern when creating namespaces
var APP = {};
(function(context){
})(APP);
Such a construct is useful when you want to make a closure - a construct helps create a private "room" for variables inaccessible from outside. See more in this chapter of "JavaScript: the good parts" book:
http://books.google.com/books?id=PXa2bby0oQ0C&pg=PA37&lpg=PA37&dq=crockford+closure+called+immediately&source=bl&ots=HIlku8x4jL&sig=-T-T0jTmf7_p_6twzaCq5_5aj3A&hl=lv&ei=lSa5TaXeDMyRswa874nrAw&sa=X&oi=book_result&ct=result&resnum=1&ved=0CBUQ6AEwAA#v=onepage&q&f=false
In the example shown on top of page 38, you see that the variable "status" is hidden within a closure and cannot be accessed anyway else than calling the get_status() method.
I'm not sure if this question is answered already, so apologies if I'm just repeating stuff.
In JavaScript, only functions introduce new scope. By wrapping your code in an immediate function, all variables you define exist only in this or lower scope, but not in global scope.
So this is a good way to not pollute the global scope.
There should be only a few global variables. Remember that every global is a property of the window object, which already has a lot of properties by default. Introducing a new scope also avoids collisions with default properties of the window object.

Difference between JavaScript function declarations?

Why does calling my JavaScript function throw an error when I call it like this
wysiwyg2();
var wysiwyg2 = function()
{
alert(1);
}
but work when I do this?
wysiwyg2();
function wysiwyg2 ()
{
alert(1);
}
You need to define your function variable first, i.e.
var wysiwyg2 = function()
{
alert(1);
}
wysiwyg2();
For a good explanation of the difference, see Why can I use a function before it’s defined in Javascript?
In the first snippet, you're trying to invoke a variable before the variable is defined.
You'd get the same problem from the following code:
test.toString();
var test = new Date;
In the second snippet, you're declaring the function without assigning it to a variable, and this results in a global declaration that is usable in earlier code.
You can think of your javascript as though it's evaluated in two passes. The first pass builds all the objects and names (and remember: functions are objects), and places them "in scope", so to speak. It's kind of like a compilation step. Then the second pass executes the code.
So your second sample works because the first pass built and "scoped" the function before execution. The first sample does not work because the function object is created as part of a variable assignment, and so it's not in scope yet when you try to call it.
You mention another situation in the comments, where the function call and definition are separated into two script blocks. That doesn't work because the engine completes both steps of one block before moving on to the next, and you tried to call the function in a block that is executed before the block where it's defined. You can call function across script blocks, but not until they are defined.
In the first one, you're declaring a function and assigning it to a variable. Thus you won't be able to call it through that variable until it's actually assigned to it.
In the second, you're declaring a named function. And can call that function from wherever (as long as it's in scope).
When entering a new execution context (which is either a function call or global code), JavaScript first goes through a variable instantiation phase during which all variable declarations and function declarations within the global code or function body are examined and create as properties of the current variable object, which is effectively a collection of all the objects that are in the current scope. In particular, any function declaration such as
function wysiwyg2 ()
{
alert(1);
}
... is fully created during this phase, while any variable declaration such as
var a = 2;
... only leads to the creation of a variable called a with a value of undefined during this phase. This is also true of a variable declaration with an assignment to a function expression, such as
var wysiwyg2 = function()
{
alert(1);
}
Only the variable instantiation takes place at this point. Once this phase is complete the rest of the code (including variable assignment) is executed sequentially.

Categories

Resources