如何创建一个简单的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 = pInt(timer / 60, 10)
        seconds = pInt(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

定时器类

cl 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 = pInt(this.time / 3600);
        let timeLeft = this.time - hours * 3600;
        let minutes = pInt(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

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

(262)
SWIFT:加快视频下载速度的技巧
上一篇
tianocore中的UEFIedk2/FmpDevicePkg在执行后崩溃
下一篇

相关推荐

  • javascript交互效果:使用JavaScript轻松实现交互效果

    JavaScript交互效果是指,当用户与网页进行交互时,网页会有相应的反应,以及动态效果。例如:鼠标移动到一个元素上,元素就会改变颜色;点击某个按钮,网页就会显示新的内容;滚动页面,某个元素就会固定在页面上,等等。…

    2023-05-07 12:38:50
    0 90 89
  • javascript 替换字符串 Hello JavaScript

    JavaScript 替换字符串可以使用 String.prototype.replace() 方法来实现。该方法接受两个参数,第一个参数是要被替换的子字符串,第二个参数是用来替换的字符串。…

    2023-05-03 03:39:37
    0 88 93
  • javascript 正则表达式 在线 John Smith

    JavaScript 正则表达式在线是一种用于搜索和替换文本的强大工具。它们可以用来验证文本,查找特定的字符串,替换文本,或者用于数据提取等等。…

    2023-05-12 14:25:27
    0 21 46
  • javascript垃圾回收机制如何优化内存使用

    JavaScript垃圾回收机制是一种自动内存管理机制,它可以帮助开发人员释放不再使用的内存。它可以跟踪变量和对象,并在不再需要时自动释放内存。…

    2023-04-30 03:43:42
    0 25 64
  • javascript的输出语句:使用JavaScript输出结果

    JavaScript的输出语句是指在网页中显示文本或其他内容的语句,常用的输出语句有document.write()、window.alert()和console.log()。…

    2023-02-09 10:17:17
    0 69 74
  • javascript注释方法:如何使用 JavaScript 注释

    示例示例注释方法有两种:单行注释和多行注释。单行注释:在要注释的代码行前加上“//”,它可以注释掉一行或者一部分代码,其代码示例如下:…

    2023-03-11 10:17:25
    0 86 40
  • javascript时钟:时钟转动,生活不断变化

    示例示例时钟是一种可以在网页中显示当前时间的功能,它可以使用来实现。下面是一个简单的时钟的示例代码:…

    2023-04-24 04:21:30
    0 64 70
  • javascript前端框架:使用Vue.js构建卓越的Web应用

    javascript前端框架是指以javascript为基础的一种用于开发Web应用程序的框架。它提供了一种结构化的方式,使开发者可以快速地构建动态网页应用程序。…

    2023-04-29 06:48:41
    0 66 68

发表评论

登录 后才能评论

评论列表(21条)