0

I am trying to build a timer. Please compare the two situations (the first one works, not the second):

What is the problem?

2 Answers 2

5

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

The second one wraps the timedCount function in jQuery ready function, hence is not available in global scope.

Fixed: http://jsfiddle.net/x7xhA/2/

1 Comment

Didn't know you're looking for a detailed explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.