I have a function that works as it should, but only if the page is reloaded after landing on the specific page.
The function is a timer function that starts to tic down from 10 to 0 when the page is loaded (it should work like this).
But I land on the page and nothing happens. When I reload the page the timer starts and works...
I have tried $(document).on and window.onload = function() but with no success.
FlowRouter.route("/waitingForPlayer", {
name: "waitingForPlayer",
action() {
BlazeLayout.render("iphone", { main: "waitingForPlayer" });
console.log("first");
window.onload = startTimer;
function startTimer(duration, display) {
console.log("second");
var timer = duration,
seconds;
setInterval(function() {
console.log("third");
seconds = parseInt(timer % 60, 10);
seconds = seconds < 10 ? "" + seconds : seconds;
display.textContent = seconds;
if (--timer < 0) {
timer = duration;
}
if (timer == 0) {
FlowRouter.go("readyForGame");
document.location.reload(true);
}
}, 1000);
}
window.onload = function() {
var fiveMinutes = 10,
display = document.querySelector("#time");
startTimer(fiveMinutes, display);
};
}
});
When the timer is = 0 the flowrouter changes view.
I think the problem is that you put onload function inside the router callback. You don't need to run window.onload inside router's callback because it's Single page application router. Try to look for onComplete event of the flow-router library. I think that action is the callback for complete event of the router.
Example:
function startTimer(duration, display) {
console.log("second");
var timer = duration, seconds;
setInterval(function() {
console.log("third");
seconds = parseInt(timer % 60, 10);
seconds = ('0' + seconds).slice(-2);
display.innerText = seconds;
if (--timer < 0) {
timer = duration;
}
if (timer == 0) {
FlowRouter.go("readyForGame");
}
}, 1000);
}
FlowRouter.route("/waitingForPlayer", {
name: "waitingForPlayer",
action: function() {
BlazeLayout.render("iphone", { main: "waitingForPlayer" });
console.log("first");
var fiveMinutes = 10,
display = document.querySelector("#time");
startTimer(fiveMinutes, display);
}
});
Related
I have a working stopwatch. When I click start button the stopwatch is starting and when I click pause button the stopwatch is paused. What I would like is when I refresh my browser to keep the current time of the stopwatch and continue from there with the same functionality. Or when I echo the stopwatch time from a database to continue from the exact time it was before is saved it.
let showTime = document.querySelector("#output");
let startTimeButton = document.querySelector("#start")
let pauseTimeButton = document.querySelector("#pause")
pauseTimeButton.style.display = "none";
let seconds = 0;
let interval = null;
const timer = () => {
seconds++;
// Get hours
let hours = Math.floor(seconds / 3600);
// Get minutes
let minutes = Math.floor((seconds - hours * 3600) / 60);
// Get seconds
let secs = Math.floor(seconds % 60);
if (hours < 10) {
hours = `0${hours}`;
}
if (minutes < 10) {
minutes = `0${minutes}`;
}
if (secs < 10) {
secs = `0${secs}`;
}
showTime.innerHTML = `${hours}:${minutes}:${secs}`;
};
startTimeButton.addEventListener("click", () => {
pauseTimeButton.style.display = "block";
startTimeButton.style.display = "none";
console.log("START TIME CLICKED");
if (interval) {
return;
}
interval = setInterval(timer, 1000);
});
// Pause function
pauseTimeButton.addEventListener("click", () => {
pauseTimeButton.style.display = "none";
startTimeButton.style.display = "block";
console.log("PAUSE TIME CLICKED");
clearInterval(interval);
interval = null;
});
<button id="start">Start</button>
<button id="pause">Pause</button>
<div id="output"></div>
You could use localStorage.
In order to save each second passed you could modify your timer function to save to localStorage:
let seconds = 0;
if (localStorage.getItem("stopwatchSeconds") != null) {
seconds = parseInt(localStorage.getItem("stopwatchSeconds"));
}
//...
const timer = () => {
//...
seconds++;
localStorage.setItem("stopwatchSeconds", seconds);
//...
};
//...
I hope this helps.
It seems like what you're looking for is localStorage. You store your stopwatch data, such as startAt, totalSeconds in the storage and when you refresh the page you can restore your stopwatch state based on the saved data: remainingTime = (startAt + totalSeconds) - currentTime
localStorage docs: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage#storing_simple_data_%E2%80%94_web_storage
I am building a pomodoro tracker in order to practice a little bit of JavaScript. It's been a while since I started this project. After this particulary problem which is implement a pause/continue functionality I abandoned the project. I really got stucked. I know programming is not easy and I will be facing many problems in the future but I really can't figure out how to solve this task. I am feeling stupid
Here is the JavaScript code:
// General Variables
let display = document.querySelector('.display');
// is the timer paused?
// let isPaused = true;
// let count = 0;
//const playPomodoro = document.querySelector('.play');
const pause = document.querySelector('.pause');
const resume = document.querySelector('.resume');
const stopPomodoro = document.querySelector('.stop');
const pomodoro = document.querySelector('#pomodoro');
const shortBreak = document.querySelector('#shortbreak');
const longBreak = document.querySelector('#longbreak')
const audioBeep = document.querySelector('#audioBeep');
const twentyFiveMinutes = 60 * 25;
const fiveMinutes = 60 * 5;
const thirtyMinutes = 60 * 30;
// Start Pomodoro timer 25 minutes
pomodoro.addEventListener('click', () => {
startTimer(twentyFiveMinutes, display);
stopClick(shortBreak, longBreak);
pause.style.display = 'block';
stopPomodoro.style.display = 'block';
});
// Start Pomodoro short break
shortBreak.addEventListener('click', () => {
startTimer(fiveMinutes, display);
stopClick(pomodoro, longBreak);
pause.style.display = 'block';
stopPomodoro.style.display = 'block';
});
// Start Pomodoro Long break
longBreak.addEventListener('click', () => {
startTimer(thirtyMinutes, display);
stopClick(pomodoro, shortBreak);
pause.style.display = 'block';
stopPomodoro.style.display = 'block';
});
// Stopping Clicks Events
function stopClick(btn1, btn2) {
btn1.classList.add('avoid-clicks');
btn2.classList.add('avoid-clicks');
}
// Remove .avoid-clicks class
function removeAvoidClick(btn1, btn2, btn3) {
btn1.classList.remove('avoid-clicks');
btn2.classList.remove('avoid-clicks');
btn3.classList.remove('avoid-clicks');
}
// main start timer function
function startTimer(duration, display) {
let timer = duration, min, sec;
let countingDown = setInterval(function() {
min = parseInt(timer / 60, 10);
sec = parseInt(timer % 60, 10);
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
display.innerHTML = min + ":" + sec;
if (--timer < 0) {
timer = duration;
}
// stops the counting variable when it hits zero
if (timer == 0) {
clearInterval(countingDown);
display.innerHTML = "00:00";
audioBeep.play();
removeAvoidClick(pomodoro,shortBreak,longBreak);
}
// Pause the clock
pause.addEventListener('click', () => {
});
// Stop the counter and set it to 00:00 when the user clicks the stop button
stopPomodoro.addEventListener('click', () => {
clearInterval(countingDown);
display.innerHTML = "00:00";
removeAvoidClick(pomodoro,shortBreak,longBreak);
});
}, 1000);
}
I will store the timer status in an object, then you activate a timer that decreses the current time left and call UI update.
let timer = {
timeLeft: 0,
running: 0,
};
function startTimer(duration) {
timer.timeLeft = duration;
if (!timer.run) {
timer.run = true;
run();
}
}
function run() {
if (timer.run) {
timer.timeLeft -= 1;
setTimeout(run, 1000)
}
}
function pauseTimer() {
timer.run = false;
}
function resumeTimer() {
if (!timer.run) {
timer.run = true;
run();
}
update();
}
function update() {
// everything you need to update in the UI from the timer object
}
var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;
btn1.addEventListener("click", surrender);
function timer () {
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
}
if (seconds === 0) {
}
}, 1000);
}
function surrender(){
clearInterval(clock);
secondsP.textContent = 0;
setTimeout(timer,2000);
}
timer();
setInterval(timer, 17000);
<html>
<head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<p id="seconds">15</p>
<button id= "btnSurrender">end now</button>
</body>
</html>
I need help with my little problem. I made a stopwatch which counts down 15 seconds. After this 15 seconds, it waits two seconds and starts again. You have option to stop counting when you want to, using "end now" button (then it'll start again after 2 sec). Now, my question is: how can I make a function which is going to stop whole counting after 3/4 rounds?
You restart the clock in surrender() using the call setTimeout(timer, 2000). All you need to do is add an if statement inside that function testing a variable that controls how many times you have run the timer, and then call/not call timer() accordingly. Here is a working example of it: https://jsfiddle.net/L38q6k5d/, but just to give you an idea of how it would work:
At the top of the js file:
var timesRun = 0
var timerInterval = null;
Inside the surrender function:
timesRun += 1 // Increment it each time the timer ends
if (timesRun > 4) { // If the timer has run less than 4 times
return; // this will stop the function here, so we dont start the timer again
}
setTimeout(timer, 2000); // Reset the timer
Inside the timer function,
if (timesRun > 1) {
clearInterval(timerInterval);
return; // end the function here
}
When starting the initial timer:
timer();
timerInterval = setInterval(timer, 17000);
Complete JS:
var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;
var timerInterval = null;
// New Code
var numberOfTimesRun = 0; // this is where we keep track of how many times the timer has run
btn1.addEventListener("click", surrender);
function timer () {
clearInterval(clock);
// New Code
if (numberOfTimesRun > 1) {
clearInterval(timerInterval);
return; // end the function here
}
// End New Code
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
numberOfTimesRun += 1; // so we know that 1 iteration of the timer has been completed
}
if (seconds === 0) {
}
}, 1000);
}
function surrender(){
clearInterval(clock);
secondsP.textContent = 0;
//New Code
numberOfTimesRun += 1;
if (numberOfTimesRun > 4) {
return; // end the function there
}
setTimeout(timer, 2000)
//End New Code
}
timer();
timerInterval = setInterval(timer, 17000);
I have a countdown timer function writed in javascript.Its working but it starts when i start the page.I want it should be start when the button clicked.
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.text(minutes + ":" + seconds);
if (--timer < 0) {
// timer = 0;
time.style.display = "none";
time2.style.display2 = "none";
redxsms.style.display = "none";
onaysms.style.display = "none";
tekraruyarionay.style.display = "block";
tekraruyarired.style.display = "block";
// time.style.display="block";
setTimeout(function () { location.reload() }, 5000);
}
}, 1000);
}
jQuery(function ($) {
var fiveMinutes = 60 * 3,
display = $('#time');
display2 = $('#time2');
startTimer(fiveMinutes, display);
startTimer(fiveMinutes, display2);
});
this is the countdown function.
<button class="ui toggle button" onclick=" hideshow(document.getElementById('onaysms')); show(this);" id="onaytoggle">
this is button when i click it should activate.
<span id="time"></span>
It starts when the page start how can i start when the button clicked?
Insert your timer call in an "onclick" event like this, it will be fired when you click on the button.
If you have several buttons on your page, i would advise you to give one an id by adding this in your html : id='timerToggle' and then replacing the $("button.toggle") in the code below by $("#timerToggle")
jQuery(function ($) {
$("button.toggle").click(function(){
var fiveMinutes = 60 * 3,
display = $('#time');
display2 = $('#time2');
startTimer(fiveMinutes, display);
startTimer(fiveMinutes, display2);
});
});
I am working on a clock that needs to display seconds into a
minutes:seconds
format.
I have worked on some auxiliary functions for display, but I have never really gotten the full display. Here is some of my code:
var time = 1500;
//Must declare timeHandler as global variable for stopTimer()
var timeHandler;
//Set intial HTML to time
document.getElementById("timer").innerHTML = display;
//Timer function for start button
function timer() {
timeHandler = setInterval(function() {
if (time > 0) {
time--;
document.getElementById("timer").innerHTML = time;
}
}, 1000);
}
//Stop function for stop button
function stopTimer() {
clearTimeout(timeHandler);
}
//Timer Display
var minutes = time/60;
var second = time%60;
var display = minutes + ":" + seconds;
HTML:
<h1> Pomodoro Clock</h1>
<!--Place holder for timer-->
<div id="timer" class="circle">Timer</div>
<!--//Start Button-->
<button onclick="setTimeout(timer, 1000);">Start</button>
<!--Stop Button-->
<button onclick="stopTimer()">Stop</button>
Thie formatTime function below will take a number of seconds, and convert it to MM:SS format (including padded zeroes):
var time = 1500;
//Must declare timeHandler as global variable for stopTimer()
var timeHandler;
//Set intial HTML to time
document.getElementById("timer").innerHTML = display;
//Timer function for start button
function timer() {
timeHandler = setInterval(function() {
if (time > 0) {
time--;
document.getElementById("timer").innerHTML = formatTime(time);
}
}, 1000);
}
//Stop function for stop button
function stopTimer() {
clearTimeout(timeHandler);
}
function formatTime(seconds) {
//Timer Display
var minutes = seconds / 60;
var second = seconds % 60;
return ('0'+minutes).substr(-2) +":"+ ('0'+seconds).substr(-2);
}
first of all you have to use clearInterval, then you don't update your display every second
check this fiddle out