I am trying to build a timer. Please compare the two situations (the first one works, not the second):
- inline javascript http://jsfiddle.net/x7xhA/
- non-inline javascript http://jsfiddle.net/x7xhA/1/
What is the problem?
I am trying to build a timer. Please compare the two situations (the first one works, not the second):
What is the problem?
This is a commonly encountered problem with users of jsFiddle's 'JavaScript section'. You see, the code that's put into the 'JavaScript section' is wrapped within a function used as a load handler, so in your second example, the real output result is this:
<script type='text/javascript'>
//<![CDATA[
$(window).load(function(){
var seconds = 0;
function timedCount() {
$("#txt").val(seconds);
seconds += 1;
setTimeout("timedCount()",1000);
}
});
//]]>
</script>
Now, timedCount isn't a global function anymore, as it's available in the scope of the load handler only, and when you use setTimeout with a string of code, this gets evaluated from the global scope.
Ways to fix this include:
change the setTimeout call to setTimeout(timedCount, 1000);
What this does, is passes the actual function object to setTimeout. Rather than evaluate the string of code, from global scope, each time, this essentially preserves the ability to call the function as scope doesn't matter anymore - you're handing the function to setTimeout.
var seconds = 0;
function timedCount() {
$("#txt").val(seconds);
seconds += 1;
setTimeout(timedCount,1000);
}
make timedCount a global function using timedCount = function() { ... };
This merely makes timedCount a global, so that when setTimeout tries to evaluate timedCount(); from the global scope, it succeeds as there is a timedCount function in the global scope.
var seconds = 0;
timedCount = function() {
$("#txt").val(seconds);
seconds += 1;
setTimeout("timedCount();",1000);
}
The second one wraps the timedCount function in jQuery ready function, hence is not available in global scope.
Fixed: http://jsfiddle.net/x7xhA/2/