如何创建一个简单的JavaScript计时器

所以,基本上我试图创建一个简单的 JS 计时器,将在 00:30 开始,一直到 00:00,然后消失。

所以,基本上我试图创建一个简单的 JS 计时器,将在 00:30 开始,一直到 00:00,然后消失。

我已经有 HTML 代码:

<div id="safeTimer">
<h2>Safe Timer</h2>
<p id="safeTimerDisplay">00:30</p>
</div>

现在我知道这将是很容易做到的,如果我做了硬编码的方式:我只是做一个函数,将改变段落的 innerHTML(“00:30”,“00:29”,“00:28”等),然后调用它每秒使用setInterval()

我将如何做到这一点的简单(不硬编码)的方式?

19

声明此函数并将其绑定到页面的onload事件

function timer(){
    var sec = 30;
    var timer = setInterval(function(){
        document.getElementById('safeTimerDisplay').innerHTML='00:'+sec;
        sec--;
        if (sec < 0) {
            clearInterval(timer);
        }
    }, 1000);
}
5

请尝试以下代码:

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.textContent = minutes + ":" + seconds;
        if (--timer < 0) {
            timer = 0;
            // timer = duration; // uncomment this line to reset timer automatically after reaching 0
        }
    }, 1000);
}
window.onload = function () {
    var time = 60 / 2, // your time in seconds here
        display = document.querySelector('#safeTimerDisplay');
    startTimer(time, display);
};

您可以看到一个 Jsfiddle 示例here

3

请尝试使用下面的代码片段。

<!DOCTYPE html>
<html>
<body>
<div id="safeTimer">
<h2>Safe Timer</h2>
<p id="safeTimerDisplay"></p>
</div>
<script>
var myVar = setInterval(function(){ myTimer() }, 1000);
var secondlimit = 30;
function myTimer() {
if(secondlimit == 0)
{
    myStopFunction();
}
document.getElementById("safeTimerDisplay").innerHTML = '00:' + zeroPad(secondlimit,2);
secondlimit = secondlimit  - 1;
}
function myStopFunction() {
    clearInterval(myVar);
}
function zeroPad(num, places) {
  var zero = places - num.toString().length + 1;
  return Array(+(zero > 0 && zero)).join("0") + num;
}
</script>
</body>
</html>
0

定时器类

class Timer {
    constructor() {
        this.time = 0;
        this.element = null;
        this.control = true;
        this.callback = null;
        this.timeLimit = 10;
    }
    set(time, id, callback = null) {
        this.time = time;
        this.element = document.getElementById(id);
        this.callback = callback;
    }
    setTimeLimit(time) {
        this.timeLimit = time;
    }
    start(type = 'COUNT_DOWN') {
        this.control = true;
        setTimeout(() => {
            if(type == 'COUNT_DOWN')
                this.countDown();
            else if(type == 'COUNT_UP') 
                this.countUp();
        }, 1000);
    }
    format() {
        let hours = parseInt(this.time / 3600);
        let timeLeft = this.time - hours * 3600;
        let minutes = parseInt(timeLeft / 60);
        timeLeft = timeLeft - minutes * 60;
        let seconds = timeLeft;
        
        hours = hours.toString();
        minutes = minutes.toString();
        seconds = seconds.toString();
    
        if (hours.length == 1)
            hours = '0' + hours;
        if (minutes.length == 1)
            minutes = '0' + minutes;
        if (seconds.length == 1)
            seconds = '0' + seconds;
        
        return hours + ':' + minutes + ':' + seconds;
    }
    countDown() {
        if(!this.control)
            return;
        let timerblock = this.element;
        timerblock.innerHTML = this.format();
        timerblock.style.display = 'block';
        if (this.time <= 59) {
            timerblock.style.color = 'red';
        }
    
        if (this.time <= 0) {
            timerblock.innerHTML = 'Time end!';
            this.callback();
            this.stop();
        }
        else {
            setTimeout(() => {
                this.countDown();
            }, 1000);
            this.time--;
        }
    }
    countUp() {
        if(!this.control)
            return;
        let timerblock = this.element;
        timerblock.innerHTML = this.format();
        timerblock.style.display = 'block';
    
        if(this.time >= this.timeLimit) {
            timerblock.innerHTML = 'Timer Limit Exceed!';
            this.callback();
            this.stop();
        }
        else {
            setTimeout(() => {
                this.countUp();
            }, 1000);
            this.time++;
        }
    }
    stop() {
        this.control = false;
    }
}

创建一个 div set 属性 id = 'timer'

<div id="timer"></div>

COUNT_DOWN 计时器中的 time = =0

超过 COUNT_UP 计时器中的时间限制

const callback = () => {
    console.log('callback function called from timer');
}

创建计时器实例

const timer = new Timer();

set 方法接受 3 个参数

时间

dom 元素 id

回调函数

timer.set(10, 'timer', callback);

最后调用 start 函数启动定时器

它需要一个字符串 'COUNT_DOWN' 或 'COUNT_UP' 默认情况下它是 'COUNT_DOWN'

timer.start('COUNT_DOWN');

停止计时器

timer.stop();
View Demo Code on Github

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(675)
在archLinux中缺少 realvnc-vnc-viewer的依赖项(libcrypt.so.1)
上一篇
iOSWidget在WidgetSearch中不可用(仅适用于 50%的用户)
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(62条)