Question

this is a simple puzzle game using html 5 drag and drop to move spans to their correct spot. A timer starts on the first drag (function drag(e)), and stops when there are no more spans left in the reserve (not shown).

(side question : is there a standard way of beautifying the (m)m : ss timer output I want, or do I have to go on as I am?)

Why does the timer() function work perfectly in chrome and firefox, and yet the seconds reset in Opera at 8 seconds? If I don't try to beautify the seconds and use the commented out line instead, it works perfectly.

Best regards!

var timerOn = false;

function drag(e) {
  if (timerOn == false) {
    timerOn = window.setInterval(function(){ timer() }, 1000);
  }
...
}

function timer() {
  var content = document.getElementById("timer").textContent.split(":");
  if (parseInt(content[1]) == 59) {
    content[0] = (parseInt(content[0]) + 1).toString();
    content[1] = "00";
  }
  else {
    var s = parseInt(content[1]) + 1;
    content[1] = (s < 10 ? "0" : "") + s.toString();
    //~ content[1] =  s.toString();
  }
  document.getElementById("timer").textContent = content[0] + ":" + content[1];
}

....

<span id="timer">0:00</span>
Était-ce utile?

La solution

Because some browsers extend JavaScript's parseInt to treat the prefix 0 to mean "octal", and 08 is an invalid octal number.

In the various places you use parseInt, give it its second argument (the radix — e.g., number base — to use), e.g. parseInt(str, 10). (This is a good idea generally, for this very reason.)

I'm surprised that you're still finding this behavior in an up-to-date browser, though, as the ECMAScript5 specification released three and a half years ago explicitly forbids extending parseInt in that way, as noted in Annex E - Additions and Changes in the 5th Edition that Introduce Incompatibilities with the 3rd Edition:

15.1.2.2: The specification of the function parseInt no longer allows implementations to treat Strings beginning with a 0 character as octal values.

...and I don't think §B.1.1 - Additional Syntax - Numeric Literals applies to parseInt.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top