Beispiel:JS-window-setinterval.html

Aus SELFHTML-Wiki
Wechseln zu: Navigation, Suche
<!doctype html>
<html lang="de">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./Beispiel:SELFHTML-Beispiel-Grundlayout.css">
<script>
'use strict';
document.addEventListener("DOMContentLoaded", function () {
	var ausgabe = document.getElementById('ausgabe'),
		backgroundColors = ['Yellow', 'Chocolate', 'LightPink', 'LightGreen', 'Aquamarine', 'LightBlue'],
		intervalId = null,
		main = document.getElementById('buehne'),
		start = document.getElementById('start'),
		stop = document.getElementById('stop');

	function startAni() {
		intervalId = window.setInterval(flashText, 1000);
		ausgabe.textContent = 'Farbwechsler aktiv';
	}

	function flashText() {
		main.style.backgroundColor = backgroundColors[
			Math.floor(Math.random() * backgroundColors.length)
		];
	}

	function stopAni() {
		window.clearInterval(intervalId);
		ausgabe.textContent = 'kein Farbwechsler';
		main.style.backgroundColor = "";
	}

	if (start && stop) {
		start.addEventListener('click', startAni);
		stop.addEventListener('click', stopAni);
	}
});
</script>
  <title>Window.setInterval</title>
</head>
<body>
  <h1>Beispiel: window.setInterval<br><span>clearInterval</span></h1>

  <main id="buehne">
    <p>Benutzen Sie die Buttons, um die Hintergrundfarbe des main-Elements alle 1000 Millisekunden ändern zu lassen.<p>
    <p>Betriebsmodus: <output id="ausgabe">kein Farbwechsler</output></p>
    <button id="start">Start</button>
    <button id="stop">Stop</button>
  </main>
</body>
</html>