【问题标题】:How can I repeat the display of this array three times?我怎样才能重复这个数组的显示三遍?
【发布时间】:2018-01-06 04:49:17
【问题描述】:

我试图每分钟显示一次锻炼,然后重复整个数组三次。到目前为止,我尝试过的一切都不起作用。我想重复三遍,然后可能会显示锻炼完成的内容。

function startMinuteTimer(duration, display) {
  var timer = duration,
    minutes, seconds;
  setInterval(function() {
    seconds = parseInt(timer % 60, 10);
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = " " + seconds;

    if (--timer < 0) {
      timer = duration;
    }
  }, 1000);
}

window.onload = function() {
  var oneMinute = 60 * 1,
    display = document.querySelector('#minutetime');
  startMinuteTimer(oneMinute, display);
};

var workouts = ["Goblet Squat", "Mountain Climber", "Single-Arm Dumbbell Swing", "T-Pushup", "Split Jump", "Dumbbell Row", "Dumbbell Side Lunge and Touch", "Pushup-Position Row", "Dumbbell Lunge and Rotation", "Dumbbell Push Press"];

setInterval(function() {
  document.getElementById("workouts").innerHTML = workouts.shift();
  //workouts[0].push();

}, 2000);
<body>
  <div>Complete as many reps as you can in <span id="minutetime">60</span> seconds!
  </div>
  <div><span id="workouts"></span> </div>
</body>

代码笔链接https://codepen.io/McComb/pen/MrOWbM

【问题讨论】:

  • 我有点困惑你想要什么。听起来您正在尝试显示一项锻炼(来自workouts 数组)一分钟,并显示该锻炼的计时器,然后切换锻炼并在最后重新启动计时器。并循环数组 3 次?
  • 没错,但是我想在数组循环三遍后停止它。
  • 酷,看看我使用Promises解决这个任务的答案:D

标签: javascript html


【解决方案1】:

好的,我稍作改动以使用 Promise 类。它非常有用,我强烈建议您学习一下,尤其是在处理异步事件时(例如 setInterval)。

所以在你的第一个函数中,我简化为 2 行,然后添加如下:

function startMinuteTimer(duration, display) {
    var timer = duration;
    var minutes, seconds;

    return new Promise( (resolve, reject) => {
        let interval = setInterval(() => {
            // timer comes in as a number, not string (no parseInt needed)
            seconds = timer % 60;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            // you don't need an empty space in this string
            display.textContent = "" + seconds;

            if (--timer < 0) {
                timer = duration;
                // clear interval so this specific instance doesn't keep looping
                clearInterval(interval);
                // tell promise we're ready to move on.
                resolve();
            }
        }, 1000);
    });
};

然后我添加了一个名为 displayWorkout 的函数,它应该循环遍历给定的锻炼标题数组,并显示它们,同时还调用你的第一个函数 startMinuteTimer 以显示每分钟的倒计时:

function displayWorkout(workouts, index=0) {

    var oneMinute = 60 * 1,
        display = document.querySelector('#minutetime');

    return new Promise( (resolve, reject) => {
        // check if there are more workouts to display
        if (index < workouts.length) {
            // put workout text in html
            document.getElementById("workouts").innerHTML = workouts[index];

            // now start the timer
            startMinuteTimer(oneMinute, display)
            .then(() => {
                // after 1 minute, call displayWorkout again to display
                // next workout in list
                return displayWorkout(workouts, index + 1);
            })
            .then(() => {
                // once the next workout is done displaying, this promise is done.
                resolve();
            });
        } else {
            // no more workouts -> this set of workouts is done.
            resolve();
        }
    });
}

最后,在onload 中,我只是设置了数组并将它异步传递给displayWorkout 三次(使用Promises)。我添加了console.log 语句,以显示第 1、2 和 3 轮何时完成:

window.onload = function() {
    var workouts = [
        "Goblet Squat", "Mountain Climber", "Single-Arm Dumbbell Swing",
        "T-Pushup", "Split Jump", "Dumbbell Row",
        "Dumbbell Side Lunge and Touch", "Pushup-Position Row",
        "Dumbbell Lunge and Rotation", "Dumbbell Push Press"
    ];

    console.log('starting round 1!');
    displayWorkout(workouts)
    .then(() => {
        console.log('starting round 2!');
        return displayWorkout(workouts);
    })
    .then(() => {
        console.log('starting round 3!');
        return displayWorkout(workouts);
    })
    .then(() => {
        console.log('done!');
    });
};

所以把它们放在一起,只需复制以下代码:

function startMinuteTimer(duration, display) {
    var timer = duration;
    var minutes, seconds;

    return new Promise( (resolve, reject) => {
        let interval = setInterval(() => {
            // timer comes in as a number, not string (no parseInt needed)
            seconds = timer % 60;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            // you don't need an empty space in this string
            display.textContent = "" + seconds;

            if (--timer < 0) {
                timer = duration;
                // clear interval so this specific instance doesn't keep looping
                clearInterval(interval);
                // tell promise we're ready to move on.
                resolve();
            }
        }, 1000);
    });
};

function displayWorkout(workouts, index=0) {

    var oneMinute = 60 * 1,
        display = document.querySelector('#minutetime');

    return new Promise( (resolve, reject) => {
        // check if there are more workouts to display
        if (index < workouts.length) {
            // put workout text in html
            document.getElementById("workouts").innerHTML = workouts[index];

            // now start the timer
            startMinuteTimer(oneMinute, display)
            .then(() => {
                // after 1 minute, call displayWorkout again to display
                // next workout in list
                return displayWorkout(workouts, index + 1);
            })
            .then(() => {
                // once the next workout is done displaying, this promise is done.
                resolve();
            });
        } else {
            // no more workouts -> this set of workouts is done.
            resolve();
        }
    });
}

window.onload = function() {
    var workouts = [
        "Goblet Squat", "Mountain Climber", "Single-Arm Dumbbell Swing",
        "T-Pushup", "Split Jump", "Dumbbell Row",
        "Dumbbell Side Lunge and Touch", "Pushup-Position Row",
        "Dumbbell Lunge and Rotation", "Dumbbell Push Press"
    ];

    console.log('starting round 1!');
    displayWorkout(workouts)
    .then(() => {
        console.log('starting round 2!');
        return displayWorkout(workouts);
    })
    .then(() => {
        console.log('starting round 3!');
        return displayWorkout(workouts);
    })
    .then(() => {
        console.log('done!');
    });
};

【讨论】:

    【解决方案2】:

    我为你做了一个新功能。有任何问题都可以告诉我。

    PD:解释在代码中

    function startMinuteTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        seconds = parseInt(timer % 60, 10);
        seconds = seconds < 10 ? "0" + seconds : seconds;
    
        display.textContent =" " + seconds;
    
        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
    }
    
    window.onload = function () {
    var oneMinute = 60 * 1,
        display = document.querySelector('#minutetime');
    startMinuteTimer(oneMinute, display);
    };
    
    
    
    
    var workouts = ["Goblet Squat", "Mountain Climber", "Single-Arm Dumbbell Swing", "T-Pushup", "Split Jump", "Dumbbell Row", "Dumbbell Side Lunge and Touch", "Pushup-Position Row", "Dumbbell Lunge and Rotation", "Dumbbell Push Press"];
    
    //Current position 
    var repetitions = 0
    
    // array length
    var _workout_length = workouts.length
    
    
    startWorkout = function(){
    
      // if the position is greater than the array size we start over
      if(repetitions >= _workout_length) 
        repetitions = 0
        
      // then we print our result and wait 2 sec before doing it again
      document.getElementById("workouts").innerHTML = workouts[repetitions]
      repetitions++
      setTimeout(function(){    
        startWorkout()
      }, 2000)  
    }
    startWorkout()
    <body>
    <div>Complete as many reps as you can in <span id="minutetime">60</span> 
    seconds!</div>
    <div><span id="workouts"></span> </div>
    </body>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      • 2014-08-11
      • 2020-06-07
      • 1970-01-01
      相关资源
      最近更新 更多