0

Can anyone tell my why this timer:

function timer() {
 var counter = 0,
 cDisplay = document.getElementById("counter");
 format = function(t) {
     var hours = Math.floor(t/360000),
         minutes = Math.floor( (t/6000) % 60),
         seconds = Math.floor( (t/100) % 60),
         ms = (Math.floor(t % 100)/100).toFixed(2);
     if (t<6000) { 
         cDisplay.innerHTML = seconds + ms.substring(1); 
     } else if (t<360000) {
         seconds = (seconds < 10) ? "0" + seconds.toString() : seconds.toString();
         cDisplay.innerHTML = minutes + ":" + seconds + ms.substring(1);
     } else {
         minutes = (minutes < 10) ? "0" + minutes.toString() : minutes.toString();
         seconds = (seconds < 10) ? "0" + seconds.toString() : seconds.toString();
         cDisplay.innerHTML = hours + ":" + minutes + ":" + seconds + ms.substring(1); 
     }
 };
 setInterval(function() {
    counter++;
    format(counter);
 },10);
}

won't start when I click on this label:

<label onClick="timer()" id="counter">Start Timer</label>

I can make it load automatically by throwing parentheses around the whole function and slapping a semi-colon on the end like this:

http://jsfiddle.net/UHjas/

but I can't figure out why it won't load with onClick="timer()". I feel like it's something really obvious that I'm missing but I just can't see it

1
  • maybe onclick instead of onClick Commented Oct 10, 2013 at 20:10

2 Answers 2

3

It is working.

Change how jsfiddle include your script from onLoad to No wrap - in <head>

Demo: http://jsfiddle.net/UHjas/3/

Basically timer() was not in global scope (check jsfiddle iframe source)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It works perfectly now. I've never had to use that option in jsfiddle before
1

That's because you define the function inside the load event, so it will only be available inside that scope.

Change the setting to No wrap - in <head> to define the function in the global scope.

http://jsfiddle.net/UHjas/1/

Comments

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.