Как создать секундомер с использованием JavaScript?
if(stopwatch >= track[song].duration)
track[song].duration
находит длительность звуковой дорожки.
Я хочу создать функцию секундомера, которая начнет считать миллисекунды, когда вы нажмете на swap
ID stopwatch
, чтобы, когда функция была нажата на определенное количество времени, функция if что-то сделает. В моем случае замените изображение. А также, что функция будет reset сама при повторном нажатии.
так что stopwatch
= current time
- clicked time
Как настроить clicked time
current time
= new Date().getTime();
? И это в миллисекундах?
$('#swap').click(function()...
Ответы
Ответ 1
jsbin.com demo
Вы увидите, что демо-код - это только старт/стоп/ reset счетчик миллисекунд. Если вы хотите сделать причудливое форматирование на тот момент, это полностью зависит от вас. Этого должно быть более чем достаточно, чтобы вы начали.
Это был интересный небольшой проект для работы. Вот как я к этому подхожу
var Stopwatch = function(elem, options) {
var timer = createTimer(),
startButton = createButton("start", start),
stopButton = createButton("stop", stop),
resetButton = createButton("reset", reset),
offset,
clock,
interval;
// default options
options = options || {};
options.delay = options.delay || 1;
// append elements
elem.appendChild(timer);
elem.appendChild(startButton);
elem.appendChild(stopButton);
elem.appendChild(resetButton);
// initialize
reset();
// private functions
function createTimer() {
return document.createElement("span");
}
function createButton(action, handler) {
var a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
handler();
event.preventDefault();
});
return a;
}
function start() {
if (!interval) {
offset = Date.now();
interval = setInterval(update, options.delay);
}
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
}
function reset() {
clock = 0;
render();
}
function update() {
clock += delta();
render();
}
function render() {
timer.innerHTML = clock/1000;
}
function delta() {
var now = Date.now(),
d = now - offset;
offset = now;
return d;
}
// public API
this.start = start;
this.stop = stop;
this.reset = reset;
};
Получить некоторые базовые HTML-обертки для него
<!-- create 3 stopwatches -->
<div class="stopwatch"></div>
<div class="stopwatch"></div>
<div class="stopwatch"></div>
Использование мертво просто оттуда
var elems = document.getElementsByClassName("stopwatch");
for (var i=0, len=elems.length; i<len; i++) {
new Stopwatch(elems[i]);
}
В качестве бонуса вы получаете программируемый API для таймеров. Здесь пример использования
var elem = document.getElementById("my-stopwatch");
var timer = new Stopwatch(elem, {delay: 10});
// start the timer
timer.start();
// stop the timer
timer.stop();
// reset the timer
timer.reset();
плагин jQuery
Что касается части jQuery, как только у вас есть хорошая композиция кода, как указано выше, запись плагина jQuery - это простой режим
(function($) {
var Stopwatch = function(elem, options) {
// code from above...
};
$.fn.stopwatch = function(options) {
return this.each(function(idx, elem) {
new Stopwatch(elem, options);
});
};
})(jQuery);
Использование плагина jQuery
// all elements with class .stopwatch; default delay (1 ms)
$(".stopwatch").stopwatch();
// a specific element with id #my-stopwatch; custom delay (10 ms)
$("#my-stopwatch").stopwatch({delay: 10});
Ответ 2
Для использования с точностью до микросекунды:
performance.now (-> Поддержка браузера)
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
function doSomething(){
for(i=0;i<1000000;i++){var x = i*i;}
}
Ответ 3
спустя несколько модификаций кода, предоставленного mace, в итоге я построил секундомер. https://codepen.io/truestbyheart/pen/EGELmv
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Stopwatch</title>
<style>
#center {
margin: 30% 30%;
font-family: tahoma;
}
.stopwatch {
border:1px solid #000;
background-color: #eee;
text-align: center;
width:656px;
height: 230px;
overflow: hidden;
}
.stopwatch span{
display: block;
font-size: 100px;
}
.stopwatch p{
display: inline-block;
font-size: 40px;
}
.stopwatch a{
font-size:45px;
}
a:link,
a:visited{
color :#000;
text-decoration: none;
padding: 12px 14px;
border: 1px solid #000;
}
</style>
</head>
<body>
<div id="center">
<div class="timer stopwatch"></div>
</div>
<script>
const Stopwatch = function(elem, options) {
let timer = createTimer(),
startButton = createButton("start", start),
stopButton = createButton("stop", stop),
resetButton = createButton("reset", reset),
offset,
clock,
interval,
hrs = 0,
min = 0;
// default options
options = options || {};
options.delay = options.delay || 1;
// append elements
elem.appendChild(timer);
elem.appendChild(startButton);
elem.appendChild(stopButton);
elem.appendChild(resetButton);
// initialize
reset();
// private functions
function createTimer() {
return document.createElement("span");
}
function createButton(action, handler) {
if (action !== "reset") {
let a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
handler();
event.preventDefault();
});
return a;
} else if (action === "reset") {
let a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
clean();
event.preventDefault();
});
return a;
}
}
function start() {
if (!interval) {
offset = Date.now();
interval = setInterval(update, options.delay);
}
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
}
function reset() {
clock = 0;
render(0);
}
function clean() {
min = 0;
hrs = 0;
clock = 0;
render(0);
}
function update() {
clock += delta();
render();
}
function render() {
if (Math.floor(clock / 1000) === 60) {
min++;
reset();
if (min === 60) {
min = 0;
hrs++;
}
}
timer.innerHTML =
hrs + "<p>hrs</p>" + min + "<p>min</p>" + Math.floor(clock / 1000)+ "<p>sec</p>";
}
function delta() {
var now = Date.now(),
d = now - offset;
offset = now;
return d;
}
};
// Initiating the Stopwatch
var elems = document.getElementsByClassName("timer");
for (var i = 0, len = elems.length; i < len; i++) {
new Stopwatch(elems[i]);
}
</script>
</body>
</html>
Ответ 4
// get DOM elements
const screen = document.querySelector(".js--screen");
const btnStart = document.querySelector(".js--btn-start");
const btnStop = document.querySelector(".js--btn-stop");
const btnReset = document.querySelector(".js--btn-reset");
const watchIcon = document.querySelector(".js--watch-icon");
const sw = new StopWatch(screen);
// setup eventlisteners
btnStart.addEventListener("click", function() {
sw.start();
this.disabled = true;
btnStop.disabled = false;
watchIcon.classList.add('animation--rotate');
});
btnStop.addEventListener("click", function() {
sw.stop();
this.disabled = true;
btnReset.disabled = false;
watchIcon.classList.remove('animation--rotate');
});
btnReset.addEventListener("click", function() {
sw.reset();
this.disabled = true;
btnStop.disabled = true;
btnStart.disabled = false;
});
// stopwatch constructor
function StopWatch(display) {
let frameId,
startTime,
times = [0, 0, 0, 0], //--> h-m-s-ms
running = false,
screen = display;
const printRunningTimer = function(resultScreen) {
resultScreen.innerHTML = formatTimes(times);
function formatTimes(times) {
const hours = pad0(times[0], 2);
const minutes = pad0(times[1], 2);
const seconds = pad0(times[2], 2);
const milliseconds = Math.floor(pad0(times[3], 2));
return '${hours}:${minutes}:${seconds}:${milliseconds}';
function pad0(value, count) {
let result = value.toString();
while (result.length < count) {
result = "0" + result;
--count;
}
return result;
}
}
};
const calculate = function(timestamp) {
const diff = timestamp - startTime;
times[3] += diff / 10; // Hundredths of a second are 100 ms
if (times[3] >= 100) {
times[3] -= 100; // reset the mil-seconds
times[2] += 1; // add one second
}
if (times[2] >= 60) {
times[2] -= 60; // reset the seconds
times[1] += 1; // add one minute
}
if (times[1] >= 60) {
times[1] -= 60; // reset the minutes
times[0] += 1; // add one hour
}
};
const step = function(timestamp) {
if (!running) return;
calculate(timestamp);
startTime = timestamp;
printRunningTimer(screen);
frameId = requestAnimationFrame(step);
};
this.start = function() {
if (running) throw new Error("Stopwatch has already started.");
running = true;
if (!startTime) startTime = performance.now();
frameId = requestAnimationFrame(step);
};
this.stop = function() {
if (!running) throw new Error("Stopwatch has not been started yet.");
// empty fileds
running = false;
startTime = null;
times = [0, 0, 0, 0];
cancelAnimationFrame(frameId);
};
this.reset = function() {
startTime = 0;
running = false;
times = [0, 0, 0, 0];
printRunningTimer(screen);
};
}
@import url("https://fonts.googleapis.com/css?family=Shadows+Into+Light");
@import url("https://fonts.googleapis.com/css?family=Orbitron");
*,
*:before,
*:after {
box-sizing: border-box;
padding: 0;
margin: 0;
}
html,
body {
color: #555;
font-size: 16px;
font-family: "Shadows Into Light", cursive;
text-rendering: optimizeLegibility;
}
.wrapper {
align-items: center;
background: #2F4858;
display: flex;
height: 100vh;
justify-content: center;
}
.btn {
background: #ff6347;
border-radius: 100px;
border: 0;
color: #f5fffa;
outline: 0;
padding: 10px 17px;
text-transform: uppercase;
transition: all 0.3s ease-in-out;
}
.btn:hover, .btn:active {
background: #ff6127;
border: 1px solid transparent;
cursor: pointer;
}
.btn:disabled {
background: #ff6347;
border: 1px solid #ff6347;
color: #f5fffa;
opacity: 0.5;
cursor: not-allowed;
}
.btn.btn-reset:not(:disabled):hover {
animation: shake 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
transform: translate3d(0, 0, 0);
}
.btn .icon {
font-size: 120%;
margin-right: 3px;
}
@media screen and (max-width: 480px) {
.btn {
font-size: 60%;
padding: 5px 8px;
}
}
.stopwatch {
align-items: center;
background: linear-gradient(to right bottom, #ff6347, #fe7756, #fc8867, #fa9978, #f7a88b);
box-shadow: 0 0 6px 3px #ff7f50;
border-radius: 50%;
display: flex;
flex-wrap: wrap;
justify-content: center;
max-width: 400px;
min-height: 400px;
}
@media screen and (max-width: 480px) {
.stopwatch {
min-width: 300px;
max-width: 300px;
min-height: 300px;
max-height: 300px;
}
}
.stopwatch__display {
align-items: center;
display: flex;
flex-direction: column;
height: 180px;
justify-content: center;
align-items: center;
overflow: hidden;
width: 100%;
}
.stopwatch__display .watch-icon {
font-size: 200%;
margin-bottom: 40px;
}
.stopwatch__display .screen {
color: #f5fffa;
font-family: "Orbitron", sans-serif;
font-size: 150%;
}
.stopwatch__controls {
align-self: flex-end;
display: flex;
margin-bottom: 120px;
margin-top: 30px;
}
.stopwatch__controls .btn:not(:first-child) {
margin-left: 2px;
}
.animation--rotate {
animation: rotateIcon 0.1s infinite ease-out 0s;
}
@keyframes shake {
10%, 90% {
transform: translate3d(-1px, 0, 0);
}
20%, 80% {
transform: translate3d(2px, 0, 0);
}
30%, 50%, 70% {
transform: translate3d(-4px, 0, 0);
}
40%, 60% {
transform: translate3d(4px, 0, 0);
}
}
@keyframes rotateIcon {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
<div class="wrapper">
<div class="stopwatch">
<div class="stopwatch__display">
<div class="watch-icon js--watch-icon">🕛</div>
<div class="screen js--screen">00:00:00:00</div>
</div>
<div class="stopwatch__controls">
<button class="btn btn-start js--btn-start">
<i class="icon ion-play"></i>
Start
</button>
<button class="btn btn-reset js--btn-reset" disabled>
<i class="icon ion-trash-a"></i>
Reset
</button>
<button class="btn btn-stop js--btn-stop" disabled>
<i class="icon ion-stop"></i>
Stop
</button>
</div>
</div>
</div>
Ответ 5
Простые и легкие часы для тебя и не забудь меня;)
var x;
var startstop = 0;
function startStop() { /* Toggle StartStop */
startstop = startstop + 1;
if (startstop === 1) {
start();
document.getElementById("start").innerHTML = "Stop";
} else if (startstop === 2) {
document.getElementById("start").innerHTML = "Start";
startstop = 0;
stop();
}
}
function start() {
x = setInterval(timer, 10);
} /* Start */
function stop() {
clearInterval(x);
} /* Stop */
var milisec = 0;
var sec = 0; /* holds incrementing value */
var min = 0;
var hour = 0;
/* Contains and outputs returned value of function checkTime */
var miliSecOut = 0;
var secOut = 0;
var minOut = 0;
var hourOut = 0;
/* Output variable End */
function timer() {
/* Main Timer */
miliSecOut = checkTime(milisec);
secOut = checkTime(sec);
minOut = checkTime(min);
hourOut = checkTime(hour);
milisec = ++milisec;
if (milisec === 100) {
milisec = 0;
sec = ++sec;
}
if (sec == 60) {
min = ++min;
sec = 0;
}
if (min == 60) {
min = 0;
hour = ++hour;
}
document.getElementById("milisec").innerHTML = miliSecOut;
document.getElementById("sec").innerHTML = secOut;
document.getElementById("min").innerHTML = minOut;
document.getElementById("hour").innerHTML = hourOut;
}
/* Adds 0 when value is <10 */
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function reset() {
/*Reset*/
milisec = 0;
sec = 0;
min = 0
hour = 0;
document.getElementById("milisec").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
document.getElementById("min").innerHTML = "00";
document.getElementById("hour").innerHTML = "00";
}
<h1>
<span id="hour">00</span> :
<span id="min">00</span> :
<span id="sec">00</span> :
<span id="milisec">00</span>
</h1>
<button onclick="startStop()" id="start">Start</button>
<button onclick="reset()">Reset</button>