[FRAGE] [Javascript] Browser reagieren verschieden bei Ausgabe - setInterval

longAdam

New member
Hallo,

ich habe ein kurzes Codeschnipsel. Eine Funktion wird im sekunden Interval ausgeführt. Dort wird die jetzige Sekunde abgefragt und ausgegeben.
Bisher soll da nichts großes passieren außer, dass mir jede Sekunde hinereinander ausgegeben wird und zusätzlich die Konsole 10x in der sekunde eine Ausgabe ausspuckt.

Jetzt verstehe ich nicht warum das unter Chrome wundervoll klappt, aber bei Firefox nichts passiert.
Könnt ihr mir helfen?
Danke

Code:
setInterval(action, 1000);

function action() {
  var sekunden = new Date().getSeconds();
  if (sekunden % 2 == 0) {
    document.write(sekunden + " ");
  }
  if (sekunden % 2 !== 0) {
    document.write(sekunden + " ");
  }

}

// Ausgabe in der Konsole //
setInterval(konsole, 100);

function konsole() {
  var sek = new Date().getSeconds();
  console.log(sek);
}
 
Du willst nicht wirklich in einem Interval mit document.write() arbeiten...? Das wird nie richtig funktionieren. Verwende einfach eine andere Ausgabetechnik (z.B. innerHTML) und es sollte funktionieren.

Dass Chrome das so macht, wie du es willst, ist eigentlich ein Bug...

Zu document.write:
http://www.w3.org/html/wg/drafts/html/CR/webappapis.html#dynamic-markup-insertion schrieb:
This method has very idiosyncratic behavior. In some cases, this method can affect the state of the HTML parser while the parser is running, resulting in a DOM that does not correspond to the source of the document (e.g. if the string written is the string "<plaintext>" or "<!--"). In other cases, the call can clear the current page first, as if document.open( ) had been called. In yet more cases, the method is simply ignored, or throws an exception. To make matters worse, the exact behavior of this method can in some cases be dependent on network latency, which can lead to failures that are very hard to debug. For all these reasons, use of this method is strongly discouraged.
 
strongly discouraged ... das wusste ich nicht.

document.write war nur zum testen da. Mit innerHTML geht es tatsächlich.

Danke für deine Hilfe.
 
Zurück
Oben