尝试为一系列时间创建倒数计时器

时间:2018-11-04 16:36:39

标签: javascript html

我正在尝试为自己构建一个小的锻炼工具。在Python中,我正在建立一个随机的时间数组,每个时间都链接到随机的练习数组。在前端(在我的html模板中),我将所有这些列在侧面的类菜单中。然后,我使用JavaScript来获取document.getElementsByClassName(“ exercises”)或document.getElementsByClassName(“ times”)的整个练习和时间。

我有一个开始按钮,单击该按钮将开始我的锻炼。我希望它:对于document.getElementsByClassName中的每个元素:运行一个倒数计时器,直到时间到期,在主屏幕上显示倒数计时器并进行锻炼。

function myfunction() {
  var times = document.getElementsByClassName('time');
  // console.log(times.item(0).innerHTML);
  var exercises = document.getElementsByClassName('exercise');
  var display = document.getElementById('currentexercise');
  for (var i = 0; i < times.length; i++) {

      var current = parseInt(times.item(i).innerHTML);
      var timeinterval = current;
      for (var j = 1; j <= timeinterval; j++) {
        
        runclock(current, i, exercises.item(i).innerHTML, display);
        current = current - 1;


      }


  }

 

  function runclock(current, i, exercise, display) {


    var x = setTimeout(function() {
      console.log(current);
      var now = new Date();
      var endoftime = new Date();
      endoftime.setSeconds(now.getSeconds() + parseInt(current));
      var distance = endoftime - now;
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);
      console.log('hit');
      document.getElementById('mytimer').innerHTML = minutes + "m " + seconds + "s ";
      display.innerHTML = exercise;
      
    }, 1000);

  }
}
{% extends "base.html" %}

{% load static %}

{% block content %}
<div class = "row">
  <div class = "col-sm-3">
    {% if workout %}
      <ul class="list-group">
        {% for exercise in workout %}
          <li class="list-group-item exercises">{{ exercise.0 }}, {{ exercise.1 }}</li>
          <li class = "hidden time">{{ exercise.1 }}</li>
          <li class = "hidden exercise">{{ exercise.0 }}</li>
        {% endfor %}
      </ul>
    {% endif %}
  </div>
  <div class = "col-sm-9">
    {% if form %}
      <h1> Spences Workout Form</h1>
      <form action="/" method="post">
          {% csrf_token %}
          {{ form.as_p }}
          <input type="submit" value="Submit">
      </form>
    {% else %}
      <h1>Spences Workout Tool</h1>
      <h3>Rounds: {{ rounds }}</h3>
      <button id = "startbutton" onclick = "myfunction()">Start</button>
    {% endif %}

    <div id = "mytimer"></div>
    <div id = "currentexercise"></div>



  </div>
</div>


{% endblock %}

这非常快地完成了每个命令,但是我希望它像常规的时钟计时器一样工作。我很难理解如何正确使用setTimeout / setInterval。请让我知道如何基本上只每秒在我的第二个forloop中运行每个“ j”。

谢谢!

2 个答案:

答案 0 :(得分:0)

setTimeout是在一段时间后异步调用另一个函数的函数。您需要编写程序来照顾它。例如,如果要执行典型的sleep(1000)操作,则应该知道需要告诉您一秒钟后要执行什么功能。

function myfunction(current=1) {
  var times = document.getElementsByClassName('time');
  // console.log(times.item(0).innerHTML);
  var exercises = document.getElementsByClassName('exercise');
  var display = document.getElementById('currentexercise');
  for (var i = 0; i < times.length; i++) {

      var end = parseInt(times.item(i).innerHTML);
      if(current <= end) {
        runclock(current, i, exercises.item(i).innerHTML, display);
      }
  }

  setTimeout(function() { myfunction(current+1) }, 1000);

  function runclock(current, i, exercise, display) {
      console.log(current);
      var now = new Date();
      var endoftime = new Date();
      endoftime.setSeconds(now.getSeconds() + parseInt(current));
      var distance = endoftime - now;
      var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((distance % (1000 * 60)) / 1000);
      console.log('hit');
      document.getElementById('mytimer').innerHTML = minutes + "m " + seconds + "s ";
      display.innerHTML = exercise;
  }
}

您可以在此处增强一些优化和设计模式,但与此相关的计时器问题应该可以解决(或类似的问题,因为如果没有可用的示例,我将不知道完整的HTML页面如何)。

答案 1 :(得分:0)

这是我的建议:

function attr(o, attrName) {
  var stop, value;
  Array.prototype.forEach.call(o.attributes, function(e){
    if (stop) return;
    if (e.nodeName === attrName) {
      value = e.nodeValue;
      stop = 1;
    }
  });
  return value;
}

function init() {
  var exercises = document.getElementsByClassName('exercises');
  Array.prototype.forEach.call(exercises, function(e){
    var dataJSON = attr(e,'data');
    var data = JSON.parse(dataJSON);
    e.innerHTML = data.name+", "+Math.floor(data.time/1000);
  });
  exercises[0].onclick();
}
init();

function seeExerciseTime (o) {
  var currentexercise = document.getElementsByClassName('currentexercise');
  if (currentexercise.length && currentexercise.length > 0) {
    currentexercise[0].classList.remove('currentexercise');
  }
  var dataJSON = attr(o,'data');
  var data = JSON.parse(dataJSON);
  o.classList.add('currentexercise');
  document.getElementById('currentexercise').innerHTML = data.name;
}

var startoftime = 0;
function myfunction() {
  startoftime = (new Date()).getTime();

  setTimeout(tick, 1000);
}

function tick() {
  var currentexercise = document.getElementsByClassName('currentexercise');
  if (currentexercise.length && currentexercise.length > 0) {
    var dataJSON = attr(currentexercise[0],'data');
    var data = JSON.parse(dataJSON);
    var now = (new Date()).getTime();
    var distance = data.time - (now - startoftime);
    if (distance < 0) distance = 0;
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    document.getElementById('mytimer').innerHTML = minutes +"m "+ seconds +"s ";
  }

  setTimeout(tick, 1000);
}
<div class = "row">
  <div class = "col-sm-3">
  Click on exercise to see the time remaining for the exercise.
      <ul class="list-group">
        <!-- {% for exercise in workout %} -->
          <li class="list-group-item exercises" data="{&quot;name&quot;:&quot;Alpha&quot;,&quot;time&quot;:60000}" onclick="seeExerciseTime(this)"></li>
          <li class="list-group-item exercises" data="{&quot;name&quot;:&quot;Beta&quot;,&quot;time&quot;:605345}" onclick="seeExerciseTime(this)"></li>
          <li class="list-group-item exercises" data="{&quot;name&quot;:&quot;Gamma&quot;,&quot;time&quot;:902323}" onclick="seeExerciseTime(this)"></li>
        <!-- {% endfor %} -->
      </ul>
  </div>
    <div id = "mytimer"></div>
    <div id = "currentexercise"></div>

  <div class = "col-sm-9">
    <!-- {% if form %}
      <h1> Spences Workout Form</h1>
      <form action="/" method="post">
          {% csrf_token %}
          {{ form.as_p }}
          <input type="submit" value="Submit">
      </form>
    {% else %} -->
      <h3>Spences Workout Tool</h1>
      <h4>Rounds: <!-- {{ rounds }} -->3</h3>
      <button id = "startbutton" onclick = "myfunction()">Start</button>
    <!-- {% endif %} -->

  </div>
</div>

我已经四处移动,以便我们可以更好地看到时间。