gpt4 book ai didi

javascript - 如何附加附加后初始化的倒计时?

转载 作者:行者123 更新时间:2023-12-03 08:57:07 25 4
gpt4 key购买 nike

我正在创建一个网络应用程序。页面加载后,例程开始,“循环”每个锻炼(不使用按键或点击)。我使用 setInterval 将不同的“锻炼”附加到 HTML。我想在每次锻炼后附加一个倒计时(让用户知道锻炼何时结束以及下一次锻炼何时开始)。

(请注意,这些 if/else 语句稍后将被 DRY 重构)

这就是我所拥有的:

$(document).ready(function() {
var counter = 470; //total length of routine in seconds
var countDown = setInterval(function(){
counter-- //decrease the counter each second
if (counter === 470) {
$(".routine").append("<p class='itemName'>Jumping Jacks!</p>");
}
else if (counter === 440) {
$(".routine").empty().append("<p class='itemName'>Take a break!</p>");
}
else if (counter === 430) {
$(".routine").empty().append("<p class='itemName'>Lounges!</p>");
}
else if (counter === 400) {
$(".routine").empty().append("<p class='itemName'>Take a Break!</p>");
}
else if (counter === 390) {
$(".routine").empty().append("<p class='itemName'>Sit Ups!</p>");
}
else if (counter === 360) {
$(".routine").empty().append("<p class='itemName'>Take break!</p>");
}
else if (counter === 350) {
$(".routine").empty().append("<p class='itemName'>Plank!</p>");
}
// will add additional workouts & breaks
else if (counter === 0) {
console.log("Finished!!");
clearInterval(countDown);
}
}, 1000);

我已经尝试过:

  • This ,但附加 span 标签而不是对其进行硬编码
  • This也是
  • this ,还附加 HTML 而不是对其进行硬编码

最佳答案

不太确定您在这里要求什么,但我修复了代码中的几个小错误,并为每个练习添加了一个“倒计时”时钟,它会倒计时直到下一次休息的秒数。JS fiddle :http://jsfiddle.net/jouef2bx/

var counter = 470; //total length of routine in seconds
var secondsLeft = 0;

var countDown = setInterval(function(){
counter--; //decrease the counter each second
secondsLeft--; // decrease time left in current exercise
$(".countdown").html("Just " + secondsLeft + " seconds to go!");
if (counter === 469) {
$(".routine").append("<p class='itemName'>Jumping Jacks!</p>");
secondsLeft = 20;
}
else if (counter === 440) {
...

既然你说你要在代码工作后干燥代码,我就原封不动地保留了你原来的算法,但通过一些分解和抽象,编码和调试确实会更简单。祝你好运。

关于javascript - 如何附加附加后初始化的倒计时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com