Я ищу простой таймер подсчета в javascript. Все сценарии, которые я нахожу, "все пение всех танцев". Я просто хочу, чтобы jQuery был бесплатным, минимальным таймером подсчета времени, который отображается в минутах и секундах. Спасибо.
Простой подсчет таймера в javascript
Ответ 1
Проверьте это:
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
<label id="minutes">00</label>:<label id="seconds">00</label>
Ответ 2
Таймер для jQuery - меньше, работает, проверен.
var sec = 0;
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval( function(){
$("#seconds").html(pad(++sec%60));
$("#minutes").html(pad(parseInt(sec/60,10)));
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="minutes"></span>:<span id="seconds"></span>
Ответ 3
Следующий код работает как таймер подсчета. Это чистый код JavaScript, который показывает hour:minute:second
. Он также имеет кнопку STOP:
<div id="timer"></div>
<div id ="stop_timer" onclick="clearInterval(timerVar)">Stop time</div>
var timerVar = setInterval(countTimer, 1000);
var totalSeconds = 0;
function countTimer() {
++totalSeconds;
var hour = Math.floor(totalSeconds /3600);
var minute = Math.floor((totalSeconds - hour*3600)/60);
var seconds = totalSeconds - (hour*3600 + minute*60);
document.getElementById("timer").innerHTML = hour + ":" + minute + ":" + seconds;
}
Ответ 4
Мне пришлось создать таймер для учителей, оценивающих работу учеников. Здесь я использовал один, который полностью основан на времени, прошедшем с начала классификации, сохраняя системное время в момент загрузки страницы, а затем сравнивая его каждые полсекунды с системным временем в этой точке:
var startTime = Math.floor(Date.now() / 1000); //Get the starting time (right now) in seconds
localStorage.setItem("startTime", startTime); // Store it if I want to restart the timer on the next page
function startTimeCounter() {
var now = Math.floor(Date.now() / 1000); // get the time now
var diff = now - startTime; // diff in seconds between now and start
var m = Math.floor(diff / 60); // get minutes value (quotient of diff)
var s = Math.floor(diff % 60); // get seconds value (remainder of diff)
m = checkTime(m); // add a leading zero if it single digit
s = checkTime(s); // add a leading zero if it single digit
document.getElementById("idName").innerHTML = m + ":" + s; // update the element where the timer will appear
var t = setTimeout(startTimeCounter, 500); // set a timeout to update the timer
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTimeCounter();
Таким образом, на самом деле не имеет значения, подвержены ли 'setTimeout' задержкам выполнения, истекшее время всегда относительно системного времени, когда оно началось, и системного времени во время обновления.
Ответ 5
Спрятавшись с кодом Bakudan и другим кодом в stackoverflow, чтобы получить все в одном. Извините, он использует jquery, но очень прост в использовании. Имеет возможность приостановить, затем возобновить его.
Обновлено: добавлено больше опций. Теперь Начать, приостановить, возобновить, reset и перезапустить. Смешайте функции для получения желаемых результатов.
Попробуйте здесь: https://jsfiddle.net/wizajay/rro5pna3/
<span id="min">00</span>:<span id="sec">00</span>
<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">
<input id="restartButton" type="button" value="Restart">
var Clock = {
totalSeconds: 0,
start: function () {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#min").text(pad(Math.floor(self.totalSeconds / 60 % 60)));
$("#sec").text(pad(parseInt(self.totalSeconds % 60)));
}, 1000);
},
reset: function () {
Clock.totalSeconds = null;
clearInterval(this.interval);
$("#min").text("00");
$("#sec").text("00");
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
if (!this.interval) this.start();
},
restart: function () {
this.reset();
Clock.start();
}
};
$('#startButton').click(function () { Clock.start(); });
$('#pauseButton').click(function () { Clock.pause(); });
$('#resumeButton').click(function () { Clock.resume(); });
$('#resetButton').click(function () { Clock.reset(); });
$('#restartButton').click(function () { Clock.restart(); });
Ответ 6
@Cybernate, я искал тот же script сегодня благодаря вашему вводу. Однако я немного изменил его для jQuery...
function clock(){
$('body').prepend('<div id="clock"><label id="minutes">00</label>:<label id="seconds">00</label></div>');
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime()
{
++totalSeconds;
$('#clock > #seconds').html(pad(totalSeconds%60));
$('#clock > #minutes').html(pad(parseInt(totalSeconds/60)));
}
function pad(val)
{
var valString = val + "";
if(valString.length < 2)
{
return "0" + valString;
}
else
{
return valString;
}
}
}
$(document).ready(function(){
clock();
});
часть css:
<style>
#clock {
padding: 10px;
position:absolute;
top: 0px;
right: 0px;
color: black;
}
</style>
Ответ 7
Примечание. Всегда добавляйте jQuery перед написанием сценариев jQuery
Шаг1: функция setInterval вызывается каждые 1000 мс (1 с)
Stpe2: В этой функции. Увеличение секунд
Шаг 3: Проверьте условия
<span id="count-up">0:00</span>
<script>
var min = 0;
var second = 00;
var zeroPlaceholder = 0;
var counterId = setInterval(function(){
countUp();
}, 1000);
function countUp () {
second++;
if(second == 59){
second = 00;
min = min + 1;
}
if(second == 10){
zeroPlaceholder = '';
}else
if(second == 00){
zeroPlaceholder = 0;
}
document.getElementById("count-up").innerText = min+':'+zeroPlaceholder+second;
}
</script>
Ответ 8
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
<label id="minutes">00</label>:<label id="seconds">00</label>
Ответ 9
Проверьте эти решения:
Ответ 10
Просто хотел поставить свои 2 цента. Я модифицировал функцию @Ajay Singh для обработки обратного отсчета и подсчета. Вот отрезок от jsfiddle.
var countDown = Math.floor(Date.now() / 1000)
runClock(null, function(e, r){ console.log( e.seconds );}, countDown);
var t = setInterval(function(){
runClock(function(){
console.log('done');
clearInterval(t);
},function(timeElapsed, timeRemaining){
console.log( timeElapsed.seconds );
}, countDown);
}, 100);
Ответ 11
Вот версия React (родной):
import React, { Component } from 'react';
import {
View,
Text,
} from 'react-native';
export default class CountUp extends Component {
state = {
seconds: null,
}
get formatedTime() {
const { seconds } = this.state;
return [
pad(parseInt(seconds / 60)),
pad(seconds % 60),
].join(':');
}
componentWillMount() {
this.setState({ seconds: 0 });
}
componentDidMount() {
this.timer = setInterval(
() => this.setState({
seconds: ++this.state.seconds
}),
1000
);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<View>
<Text>{this.formatedTime}</Text>
</View>
);
}
}
function pad(num) {
return num.toString().length > 1 ? num : `0${num}`;
}
Ответ 12
Расширение от @Chandu с добавлением некоторого пользовательского интерфейса:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<style>
button {
background: steelblue;
border-radius: 4px;
height: 40px;
width: 100px;
color: white;
font-size: 20px;
cursor: pointer;
border: none;
}
button:focus {
outline: 0;
}
#minutes, #seconds {
font-size: 40px;
}
.bigger {
font-size: 40px;
}
.button {
box-shadow: 0 9px #999;
}
.button:hover {background-color: hotpink}
.button:active {
background-color: hotpink;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
</style>
<body align='center'>
<button onclick='set_timer()' class='button'>START</button>
<button onclick='stop_timer()' class='button'>STOP</button><br><br>
<label id="minutes">00</label><span class='bigger'>:</span><label id="seconds">00</label>
</body>
</html>
<script>
function pad(val) {
valString = val + "";
if(valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
totalSeconds = 0;
function setTime(minutesLabel, secondsLabel) {
totalSeconds++;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function set_timer() {
minutesLabel = document.getElementById("minutes");
secondsLabel = document.getElementById("seconds");
my_int = setInterval(function() { setTime(minutesLabel, secondsLabel)}, 1000);
}
function stop_timer() {
clearInterval(my_int);
}
</script>
Выглядит так:
Ответ 13
Вот .padStart()
использования .padStart()
:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' />
<title>timer</title>
</head>
<body>
<span id="minutes">00</span>:<span id="seconds">00</span>
<script>
const minutes = document.querySelector("#minutes")
const seconds = document.querySelector("#seconds")
let count = 0;
const renderTimer = () => {
count += 1;
minutes.innerHTML = Math.floor(count / 60).toString().padStart(2, "0");
seconds.innerHTML = (count % 60).toString().padStart(2, "0");
}
const timer = setInterval(renderTimer, 1000)
</script>
</body>
</html>
Метод padStart() дополняет текущую строку другой строкой (при необходимости повторяется), чтобы полученная строка достигла заданной длины. Заполнение применяется с начала (слева) текущей строки.