javascript - 不能让函数再次运行
问题描述
我做了一个会达到零的计时器。当它达到零时,让计时器再次运行。计时器回到起始编号,但不再运行。当我再次调用它时,数字也开始跳跃。编码:
var timerPlace = document.getElementById('timer');
var timerP = document.getElementById('timerHard');
var stopTimer;
var toStop;
function timeMed() {
console.log('im in!')
var counter = 0;
var timeLeft = 5;
timerPlace.innerHTML = '00:45';
function timeIt() {
console.log('here')
counter++
timerPlace.innerHTML = convertSeconds(timeLeft - counter);
if (timerPlace.innerHTML == '00:00') {
clearInterval(stopTimer);
resetExercise();
timeMed();
}
}
function convertSeconds(s) {
var sec = s % 60;
var min = Math.floor((s % 3600) / 60);
return ('0' + min).slice(-2) + ':' + ('0' + sec).slice(-2);
}
if (!stopTimer) {
stopTimer = setInterval(timeIt, 1000);
}
}
解决方案
现代 ES6 方法和最佳实践。
我决定抓住机会,考虑到 Javascript 的最佳实践,对您的代码进行一些重构。
我添加了解释代码和工程注意事项的注释。
计时器的基线取自这里的优秀答案:https ://stackoverflow.com/a/20618517/1194694
// Using destructuring on the paramters, so that the keys of our configuration object,
// will be available as separate parameters (avoiding something like options.duraitons and so on.
function startTimer({duration, onUpdate , infinite}) {
let timer = duration, minutes, seconds;
let interval = setInterval(function () {
minutes = parseInt(timer / 60);
seconds = parseInt(timer % 60);
// you can also add hours, days, weeks ewtc with similar logic
seconds = seconds < 10 ? `0${seconds}` : seconds;
minutes = minutes < 10 ? `0${minutes}` : minutes;
// calling your onUpdate function, passed from configuraiton with out data
onUpdate({minutes, seconds});
if (--timer < 0) {
// if infinite is true - reset the timer
if(infinite) {
timer = duration;
} else {
// Clearing the interval + additonal logic if you want
// I would also advocate implementing an onEnd function,
// So that you'll be able to decide what to do from configuraiton.
clearInterval(interval);
}
}
}, 1000);
}
const duration = 5;
const displayElement = document.querySelector("#timer");
startTimer({
duration,
onUpdate: ({minutes, seconds}) => {
// now you're not constraint to rendering it in an element,
// but can also Pass on the data, to let's say your analytics platform, or whatnot
displayElement.textContent = `${minutes}:${seconds}`;
},
infinite: true
});
<div id="timer">
</div>
推荐阅读
- r - 无法将形状添加到 geom_points
- filter - 使用 FILTER 过滤没有直接关系的不同表时的奇怪行为?
- r - R:在集群上运行 R 时出现内存限制错误
- swagger - Swagger UI - 请求未经授权然后隐藏试用按钮
- c++ - MFC。查询 CInternetSession 类中的 GetFtpConnection 方法
- netty - 带有 setReuseAddress(true) 的 gRPC Java 服务器?
- php - 单击发送按钮时,页面未显示文本已成功发送
- c# - ASP.NET Core 模型按国外字段排序
- java - Controller.Controller 中的错误字段存储库需要找不到类型为“Controller.Repository”的 bean
- c++ - 带有 CMake 的 OpenSSL - 未知选项:构建 openSSL 时的 --sysroot