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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
loadhandler, so in your second example, the real output result is this:Now,
timedCountisn’t a global function anymore, as it’s available in the scope of theloadhandler only, and when you usesetTimeoutwith a string of code, this gets evaluated from the global scope.Ways to fix this include:
change the
setTimeoutcall tosetTimeout(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 tosetTimeout.make
timedCounta global function usingtimedCount = function() { ... };This merely makes
timedCounta global, so that whensetTimeouttries to evaluatetimedCount();from the global scope, it succeeds as there is atimedCountfunction in the global scope.