计时器和本地存储问题

时间:2018-08-26 03:11:28

标签: javascript local-storage

我对Javascript和Web编程非常陌生,目前正在学习localStorage,并且找到了一些代码,并尝试对其进行修改。我想做的是,当设置的时间到了时,我想调用另一个名为任何功能的功能。请帮忙。

注意:如果在堆栈溢出规则方面有任何问题,请告诉我。我将编辑并删除问题。

JS

var finishTime;
var timerLength = 10;
var timeoutID;
dis.innerHTML = "Time Left: " + timerLength;


if(localStorage.getItem('myTime')){
    Update();

}


$('#save').click(function () {
    localStorage.setItem('myTime', ((new Date()).getTime() + timerLength * 1000));
    if (timeoutID != undefined) window.clearTimeout(timeoutID);
    Update();

});

function Update() {
    finishTime = localStorage.getItem('myTime');
    var timeLeft = (finishTime - new Date().getTime());
    dis.innerHTML = "Time Left: " + Math.max(timeLeft/1000,0);

    if(timeLeft <= 0){
      console.log('please work');
    }else{
       timeoutID = window.setTimeout(Update, 100);
    }
}  

视图

<p id="display">Time Left
    <p>
        <button id="start">Start</button>

1 个答案:

答案 0 :(得分:1)

没有尝试您的代码,但是这一行:

var timeLeft = (finishTime - new Date());

不应该吗?

var timeLeft = (finishTime - new Date().getTime());

添加了.getTime()

编辑: function Update() { finishTime = localStorage.getItem('myTime'); var timeLeft = (finishTime - new Date().getTime()); dis.innerHTML = "Time Left: " + Math.max(timeLeft/1000,0);

if (timeLeft <= 0){ localStorage.removeItem('myTime'); //<=remove whateversomethingfunctuin(); // console.log('Seems'); } else { //call only when needed timeoutID = window.setTimeout(Update, 100); } }