暂停和恢复本地存储中的计数值

时间:2018-09-28 10:31:23

标签: javascript jquery html local-storage

我正在将此代码用于倒数计时器进行测验。它的工作正常。在此,我需要添加两个按钮,一个是“暂停”按钮,另一个是“继续”按钮。当我单击“暂停”按钮时,它是停止时间;当我单击“恢复”按钮时,它是从我暂停时间开始的时间。

我已经尝试过此代码。它不起作用。

HTML代码

<div class="div__time">
    <div style="display: none;" id="overall_time"></div>
    <div id="overall_times"></div>
    <div class="total_time"></div>
</div>
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">

JS代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>
<script>
    var speaking_ms = "00:00:10";
    var speaking_ms_arr = speaking_ms.split(":");
    var speaking_time_min_sec = (+speaking_ms_arr[0]) * 60 * 60 + (+speaking_ms_arr[1]) * 60 + (+speaking_ms_arr[2]);
    var speaking_time_min_sec = parseInt(speaking_time_min_sec) + 1;

    var speaking_value;

    if (localStorage.getItem("speaking_counter")) {
        if (localStorage.getItem("speaking_counter") <= 0) {
            speaking_value = speaking_time_min_sec;
        } else {
            speaking_value = localStorage.getItem("speaking_counter");
        }
    } else {
        speaking_value = speaking_time_min_sec;
    }

    document.getElementById('overall_time').innerHTML = speaking_value;

    var speaking_counter = function() {
        if (speaking_value <= 0) {
            localStorage.setItem("speaking_counter", speaking_time_min_sec);
        } else {
            speaking_value = parseInt(speaking_value) - 1;
            localStorage.setItem("speaking_counter", speaking_value);
        }
        document.getElementById('overall_time').innerHTML = speaking_value;
        if (speaking_value == 0) {
            localStorage.setItem("speaking_counter", speaking_value);
            setTimeout(function() {
                clearInterval(interval);
            }, 1000);
        }

        var hours = Math.floor(speaking_value / 3600);
        var minutes = Math.floor(speaking_value % 3600 / 60);
        var seconds = Math.floor(speaking_value % 3600 % 60);
        var red_time = hours + ' : ' + minutes + ' : ' + seconds;
        document.getElementById('overall_times').innerHTML = red_time;
    };

    var interval = setInterval(function() {
        speaking_counter();
    }, 1000);

    var Clock = {
        pause: function() {
                clearInterval(this.interval);
                delete this.interval;
            },

            resume: function() {
                if (!this.interval) this.start();
            }
    };

    $('#pauseButton').click(function() { Clock.pause(); });
    $('#resumeButton').click(function() { Clock.resume(); });
</script>

Fiddle Link

谢谢。

4 个答案:

答案 0 :(得分:1)

我更改了小提琴中代码的末尾,它起作用了:https://jsfiddle.net/bohv0j9w/5/

    var Clock = {
        pause: function() {
                clearInterval(interval);
                interval = null;
            },

            resume: function() {
                if (!interval) interval = setInterval(speaking_counter, 1000);
            }
    };

document.querySelector('#pauseButton').addEventListener("click", Clock.pause);
document.querySelector('#resumeButton').addEventListener("click", Clock.resume);

在您的版本中,this.internal是未定义的,您可能想了解js中的“ this”和范围。 $(...)是需要lib jquery(未包含在小提琴中)的语法,vanilla js等效于“ document.querySelector”,您应该阅读有关此功能的MDN文章。 最后,您的语法有点老套了。如果您使用的是localStorage,则您的目标不是很老的浏览器,也许应该避免使用jquery并使用诸如“ const”之类的关键字。

答案 1 :(得分:1)

以下是您的错误。 (Fiddle link

var Clock = {
    pause: function() {
            clearInterval(this.interval);//(this.interval is undefined, replace it with interval)
                          ^^^^
            delete this.interval;//(this.interval is undefined, replace it with interval)
                   ^^^^
        },

        resume: function() {
            if (!this.interval) this.start();//(this.interval is undefined, replace it typeof interval === undefined to check whether interval exists or not)
                 ^^^^
                                ^^^^^^^^^^^ //(this.start() is also not defined, replace it with start() and move `var interval = setInterval(fun.....` into new start function)
        }
};

看下面的代码。

var speaking_ms = "00:00:10";
var speaking_ms_arr = speaking_ms.split(":");
var speaking_time_min_sec = (+speaking_ms_arr[0]) * 60 * 60 + (+speaking_ms_arr[1]) * 60 + (+speaking_ms_arr[2]);
var speaking_time_min_sec = parseInt(speaking_time_min_sec) + 1;

var speaking_value;

if (localStorage.getItem("speaking_counter")) {
    if (localStorage.getItem("speaking_counter") <= 0) {
        speaking_value = speaking_time_min_sec;
    } else {
        speaking_value = localStorage.getItem("speaking_counter");
    }
} else {
    speaking_value = speaking_time_min_sec;
}

document.getElementById('overall_time').innerHTML = speaking_value;

var speaking_counter = function() {
    if (speaking_value <= 0) {
        localStorage.setItem("speaking_counter", speaking_time_min_sec);
    } else {
        speaking_value = parseInt(speaking_value) - 1;
        localStorage.setItem("speaking_counter", speaking_value);
    }
    document.getElementById('overall_time').innerHTML = speaking_value;
    if (speaking_value == 0) {
        localStorage.setItem("speaking_counter", speaking_value);
        setTimeout(function() {
            clearInterval(interval);
        }, 1000);
    }

    var hours = Math.floor(speaking_value / 3600);
    var minutes = Math.floor(speaking_value % 3600 / 60);
    var seconds = Math.floor(speaking_value % 3600 % 60);
    var red_time = hours + ' : ' + minutes + ' : ' + seconds;
    document.getElementById('overall_times').innerHTML = red_time;
};

var start = function() {
  interval = setInterval(function() {
      speaking_counter();
  }, 1000);
}

var Clock = {
    pause: function() {
            clearInterval(interval);
            delete interval;
        },

        resume: function() {
            if (typeof interval === 'undefined') start();
        }
};

$('#pauseButton').click(function() { Clock.pause(); });
$('#resumeButton').click(function() { Clock.resume(); });
start();

答案 2 :(得分:1)

我已经解决了您的解决方案,并实现了您要实现的目标。我解决了您的解决方案中的小问题。 1.您正在使用它来访问时间间隔变量,该时间间隔变量不是您要访问其的时钟对象的一部分。 2.您在不是时钟对象一部分的时钟对象的恢复功能中使用了this.start()函数。 3.用于定义事件的JQuery未包含在小提琴中。尽管它包含在问题中粘贴的代码中。 html:

<html>

<head>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>

</head>
<body>
<div class="div__time">
    <div style="display: none;" id="overall_time"></div>
    <div id="overall_times"></div>
    <div class="total_time"></div>
</div>
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">
</body>

js:

 var speaking_ms = "00:00:10";
    var speaking_ms_arr = speaking_ms.split(":");
    var speaking_time_min_sec = (+speaking_ms_arr[0]) * 60 * 60 + (+speaking_ms_arr[1]) * 60 + (+speaking_ms_arr[2]);
    var speaking_time_min_sec = parseInt(speaking_time_min_sec) + 1;

    var speaking_value;

    if (localStorage.getItem("speaking_counter")) {
        if (localStorage.getItem("speaking_counter") <= 0) {
            speaking_value = speaking_time_min_sec;
        } else {
            speaking_value = localStorage.getItem("speaking_counter");
        }
    } else {
        speaking_value = speaking_time_min_sec;
    }

    document.getElementById('overall_time').innerHTML = speaking_value;

    var speaking_counter = function() {
        if (speaking_value <= 0) {
            localStorage.setItem("speaking_counter", speaking_time_min_sec);
        } else {
            speaking_value = parseInt(speaking_value) - 1;
            localStorage.setItem("speaking_counter", speaking_value);
        }
        document.getElementById('overall_time').innerHTML = speaking_value;
        if (speaking_value == 0) {
            localStorage.setItem("speaking_counter", speaking_value);
            setTimeout(function() {
                clearInterval(interval);
            }, 1000);
        }

        var hours = Math.floor(speaking_value / 3600);
        var minutes = Math.floor(speaking_value % 3600 / 60);
        var seconds = Math.floor(speaking_value % 3600 % 60);
        var red_time = hours + ' : ' + minutes + ' : ' + seconds;
        document.getElementById('overall_times').innerHTML = red_time;
    };

    var interval = setInterval(function() {
        speaking_counter();
    }, 1000);


    var Clock = {
        pause: function() {
                clearInterval(interval);
                delete interval;
            },

            resume: function() {

                    interval = setInterval(function() {
                        speaking_counter();
                    }, 1000);

            }
    };

    $('#pauseButton').click(function() { Clock.pause(); });
    $('#resumeButton').click(function() { Clock.resume(); });

以下是小提琴链接:JS Fiddle

答案 3 :(得分:1)

到目前为止,您已经获得了很多答案,我想再举一个例子,以便您考虑替代架构。一定要阅读scopes and closuresthis的用法。此外,您不需要jQuery即可使用此功能。仅在需要时导入像jQuery这样的大型库。在这种情况下,document.getElementByIdaddEventListener一样好。

还有更多令人兴奋的方式来处理倒数(包括使用递归),但以下是将Clock设想为单个对象的示例。这样可以使您更好地控制时钟,并使其可重用。

您可以在时钟上定义用于管理时间间隔,减少倒数,暂停,恢复,启动和重置时钟的功能。我为每个按钮添加了按钮,以便您了解其工作原理。还要注意,我注释掉了localStorage来表明它无需存储即可工作,但是主要是因为未授予StackOverflow中的代码片段使用localStorage的权限,因此它会崩溃,但是您可以在此处运行此代码照原样。

var Clock = {
  speaking_value: 10,
  interval: -1,
  countdown: function() {
    speaking_value = this.speaking_value;
    if (speaking_value <= 0) {
      //localStorage.setItem("speaking_counter", 0);
    } else {
      speaking_value = parseInt(speaking_value) - 1;
      //localStorage.setItem("speaking_counter", speaking_value);
    }
    document.getElementById('overall_time').innerHTML = speaking_value;
    if (speaking_value == 0) {
    //localStorage.setItem("speaking_counter", speaking_value);
      var self = this;
      setTimeout(function() {
        clearInterval(self.interval);
      }, 1000);
    }
    this.speaking_value = speaking_value;
    this.updateClock();
  }, 
  paused: false,
  pause: function() {
    clearInterval(this.interval);
    this.paused = true;
  },
  resume: function() {
    if (this.paused) { 
      this.paused = false;
      this.tick();    
    }
  },
  updateClock: function() {
    speaking_value = this.speaking_value;
    var hours = Math.floor(speaking_value / 3600);
    var minutes = Math.floor(speaking_value % 3600 / 60);
    var seconds = Math.floor(speaking_value % 3600 % 60);
    var red_time = hours + ' : ' + minutes + ' : ' + seconds;
    document.getElementById('overall_times').innerHTML = red_time;
  },
  tick: function() {
    var self = this;
    this.interval = setInterval(function() {
      self.countdown()
    }, 1000)
  },
  start: function() {
    this.updateClock();
    this.tick();
  },
  reset: function(){
    clearInterval(this.interval);
    this.speaking_value = 10;
    this.updateClock();
  }
};

Clock.updateClock();

document.getElementById('startButton').addEventListener('click', function() { Clock.start(); });

document.getElementById('pauseButton').addEventListener('click', function() { Clock.pause(); });

document.getElementById('resumeButton').addEventListener('click', function() { Clock.resume(); });

document.getElementById('resetButton').addEventListener('click', function() { Clock.reset(); });
<div class="div__time">
    <div style="display: none;" id="overall_time"></div>
    <div id="overall_times"></div>
    <div class="total_time"></div>
</div>
<input id="startButton" type="button" value="Start">
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">
<input id="resetButton" type="button" value="Reset">