Beispiel:JS-Anwendung-Timer.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">
  <title>Beispiel: Timer</title>
  <style>
    .timer {
      border-radius: 0 .5em .5em;
      border: 1px solid;
      padding: .5em;
      margin: .5em;
      background-color: #fffbf0; 
      border-color: #e7c157;
      width: 4em;
      font-size: 1.5em;
    }
  </style>
<script>
'use strict';  
(function () {
  function init() {
    window.addEventListener('load',starteCountdown);
    document.getElementById('reset').addEventListener("click",starteCountdown);  
  }
  
function starteCountdown () {
  new countdown(20, 'counter1');
  new countdown(10, 'counter2');
}
 
Function.prototype.Timer = function (interval, calls, onend) {
  var count = 0;
  var payloadFunction = this;
  var startTime = new Date();
  var callbackFunction = function () {
    return payloadFunction(startTime, count);
  };
  var endFunction = function () {
    if (onend) {
      onend(startTime, count, calls);
    }
  };
  var timerFunction =  function () {
    count++;
    if (count < calls && callbackFunction() != false) {
      window.setTimeout(timerFunction, interval);
    } else {
      endFunction();
    }
  };
  timerFunction();
};
 
function leadingzero (number) {
    return (number < 10) ? '0' + number : number;
}
function countdown (seconds, target) {
  var element = document.getElementById(target);
  var calculateAndShow = function () {
    if (seconds > 0) {
      var h = Math.floor(seconds / 3600);
      var m = Math.floor((seconds % 3600) / 60);
      var s = seconds % 60;
      element.innerHTML=
        leadingzero(h) + ':' +
        leadingzero(m) + ':' +
        leadingzero(s);
      seconds--;
    } else {
      return false;
    }
  };
  var completed = function () {
    element.innerHTML = "<strong>Liftoff!<\/strong>";
  };
  calculateAndShow.Timer(1000, Infinity, completed);
}

  
  document.addEventListener('DOMContentLoaded',init);
}());
</script>
</head>
 
<body>
  <h1>Beispiel: Timer</h1>
 
  <main>
    <h2>The Final Countdown</h2>
    <p class="timer" id="counter1"></p>
    <p class="timer" id="counter2"></p>
    <button id="reset">Neu starten!</button> 
  </main>
</body>
</html>