Repeat timer infinite amount of times - javascript

I am trying to add a countdown timer to my Shopify checkout using Google Optimize. I got this to work using the following HMTL & JS. Taken from here
However once the timer finishes and I reload the page it starts from 17 seconds instead of 5 minutes.
Is there a way to get this to repeat the timer from 5 minutes once it hits 0?
document.getElementById('timer').innerHTML =
05 + ":" + 00;
startTimer();
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){
return
}
document.getElementById('timer').innerHTML =
m + ":" + s;
console.log(m)
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
if (sec < 0) {sec = "59"};
return sec;
}
<div>Your cart is reserved for <span id="timer"></span></div>
If you could give the answer like you are talking to a complete beginner it would be greatly appreciated.
Looks like I have a lot to learn!

Welcome to StackOverflow. This should help out...
//JAVASCRIPT
startTimer(5); // SPECIFY AMOUNT OF MINUTES OR NO PARAMETER FOR DEFAULT 5
function startTimer(minutes = 5){
var timeout = minutes * 60000;
var ms = timeout;
var interval = setInterval(function(){
ms -= 1000;
if(ms >= 0) {
var d = new Date(1000*Math.round(ms/1000));
document.getElementById('timer').innerHTML = getMS(d);
} else {
startTimer(5); // MAKE TIMER RESTART AGAIN FOR 5 MINS
// clearInterval(interval); // TO MAKE TIMER STOP UPON REACHING 0:00
}
}, 1000);
}
function getMS(d){
return pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds());
}
function pad(i) {
return ('0'+i).slice(-2);
}
<!--HTML -->
<body>
<div>Your cart is reserved for <span id="timer"></span></div>
</body>

In javascript the setInterval function allow you to make anything you want every fixed ms.
interval = setInterval(() => {
console.log('Waited for 5m');
// Do whatever you want
console.log('Waiting for 5m again...');
}, 300000);
// To stop the interval
clearInterval(interval);

Related

JavaScript countdown timer counting past zero

This might be a really simple thing to ask but I've got a JavaScript countdown timer, but I can't stop it from counting past 0:00. Instead of stopping at this point, it will continue to -1:59 etc.
I'd also like it to play a beeping sound (which can be found here) when the timer reaches zero.
This is the code I've got so far:
<div class="stopwatch">
<div class="circle">
<div class="time" id="timer"></div>
</div>
</div>
<script>
document.getElementById('timer').innerHTML =
02 + ":" + 30;
startTimer();
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
document.getElementById('timer').innerHTML =
m + ":" + s;
console.log(m)
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
if (sec < 0) {sec = "59"};
return sec;
}
</script>
Any help on this would be appreciated.
To stop the counter when it reaches zero you have to stop calling the startTimer() function. In the following snippet I have implemented a check to do exactly that.
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
document.getElementById('timer').innerHTML =
m + ":" + s;
console.log(m)
// Check if the time is 0:00
if (s == 0 && m == 0) { return };
setTimeout(startTimer, 1000);
}

Executing a function once when YouTube API iFrame hits over 75% of the video

I am attempting to run a function when an iFrame is playing via the YouTube API, but it executes way too many times. I have tried to flag the function with a bool to no avail. I've been stuck on this for a few hours. Please help, lol.
How can I limit this function to run only once while the video is playing?
var completedMajority = false;
function onPlayerStateChange(event, tID, tName, isThereAnExam, time) {
if (event.data == 1) { // playing
myTimer = setInterval( function(){
var time;
time = player.getCurrentTime();
minutes = parseInt(time / 60, 10);
seconds = parseInt(time % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
timeDuration = localStorage['timeDuration'];
majorityOfVid = timeDuration / 4 * 3;
console.log(time);
if (!completedMajority && time >= majorityOfVid) {
completedMajority = true;
majorityOfModuleCompleted(isLive, baseURL)
}
console.log(completedMajority);
$('#thisIsTheFinalCountdown').text(minutes + ":" + seconds);
}, 100);
}
else { // not playing
clearInterval(myTimer);
}
the whole function, before your first if, should be wrapped in:
if (!completedMajority) {
[...]
}

Adding time on button click to a count down timer

Im creating a countdown timer which starts at 3mins and 30secs.
When the timer reaches 0 the initial 3:30 timer will be repeated.
This happens until the user presses a button, which will add 1:45 to the timer and pause the timer until the user decides to resume the timer from the new value. Eg ( 3:30 + 1:45 = 5:15).
Now I have got the first 2 step to work with my current code, but I'm having a lot of issues with the 3rd part. Once the user clicks the add 1.45 button the count works, but only up until a certain point. After this point it will start to display a negative integer.
I'm sure there is an easier way to write this code. I have really overcomplicated this. Any suggestions would be appreciated.
//Define vars to hold time values
let startingMins = 3.5;
let time = startingMins * 60;
//define var to hold stopwatch status
let status = "stopped";
//define var to holds current timer
let storeTime = null;
//define Number of sets
let setNum = 1;
//Stop watch function (logic to determin when to decrement each value)
function stopwatch () {
minutes = Math.floor(time / 60);
let seconds = time % 60;
seconds = seconds < 10 ? '0' + seconds : seconds;
storeTimer = minutes + ":" + seconds; //Store time in var
storeTime = minutes + "." + seconds; //Store time in var
//Display updated time values to user
document.getElementById("display").innerHTML = storeTimer;
time--;
// When timer reachers 0 secs the inital 3:30 countdown will begin again.
if (time <= 0) {
startingMins = 3.5;
time = startingMins * 60;
minutes = Math.floor(time / 60);
seconds = time % 60;
seconds = seconds < 10 ? '0' + seconds : seconds;
setNum++;
//console.log(setNum);
}
}
function StartStop() {
if(status === "stopped") {
//start watch
interval = window.setInterval(stopwatch, 100);
var startButton = document.getElementById("start");
document.getElementById("start").innerHTML = "Pauce";
//startButton.style.display = "none"
status = "start";
//console.log(time);
}
else {
window.clearInterval(interval);
document.getElementById("start").innerHTML = "Start";
status = "stopped";
console.log(storeTime);
}
}
function pauceAdd () {
if(status === "stopped") {
//start watch
interval = window.setInterval(stopwatch, 1000);
var zukButton = document.getElementById("pauceAdd");
status = "start";
}
else {
window.clearInterval(interval);
status = "stopped";
console.log("store time " + storeTime);
let time = +storeTime + +1.45; //store time is 3.30 adding 4.75
console.log("store time2 " + time); // correct result 4.75
minutes = Math.floor(time);/// convert time from Mins (4.75) to seconds (475)
let seconds = time % 60; // 5
if (seconds < 60 ) { // if the Stored time is greater than 60 secs add 1 minute to the timer
minutes++;
seconds = seconds * 100;
console.log("secs updated = " + seconds ); // seconds updated (475)
if (seconds <= 460) {
seconds = Math.floor(seconds - 460);
console.log("seconds 2 == " + seconds)
}
else if (seconds > -60) { // Stuck here
seconds = seconds + 60;// Stuck here
}// Stuck here
else {
seconds = Math.floor(seconds - 460);
console.log("seconds 2 = " + seconds)
}
}
if (seconds < 1) {
seconds = seconds + 60;
minutes = minutes - 1;
}
seconds = seconds < 10 ? + seconds : seconds;
console.log("mins updated = " + minutes + "__________________________-");
//Display updated time values to user
document.getElementById("display").innerHTML = minutes + ":" + seconds;
}
}
function reset () {
//window.clearInterval(storeTime);
window.clearInterval(interval);
startingMins = 3.5;
time = startingMins * 60;
minutes = Math.floor(time / 60);
seconds = time % 60;
seconds = seconds < 10 ? '0' + seconds : seconds;
status = "stopped";
setNum = 1;
var startButton = document.getElementById("start");
startButton.style.display = "inline-block";
document.getElementById("display").innerHTML = "3:30";
document.getElementById("start").innerHTML = "Start";
}
I might have taken the requirements a bit too literally:
Im creating a countdown timer which starts at 3mins and 30secs.
When the timer reaches 0 the initial 3:30 timer will be repeated.
This happens until the user presses a button, which will add 1:45 to the timer and pause the timer until the user decides to resume the
timer from the new value. Eg ( 3:30 + 1:45 = 5:15).
There's a trick to countdown timers. You have to use timestamps to find out how much time ACTUALLY elapsed. You can't trust that your interval will fire exactly every second. In fact, it almost always fires a bit later (in my tests, about 2-3 milliseconds, but I was logging to the console as well, so that might have skewed the test).
let interval, timestamp;
let countdown = 210000;
document.addEventListener("DOMContentLoaded", () => {
document
.querySelector("button")
.addEventListener("click", (event) => toggleState(event.target));
});
function toggleState({ dataset }) {
timestamp = Date.now();
if (dataset.state == "running") {
clearInterval(interval);
countdown += 105000;
updateDisplay(dataset, "paused");
} else {
interval = setInterval(() => updateCountdown(dataset), 100);
updateDisplay(dataset, "running");
}
}
function updateCountdown(dataset) {
const now = Date.now();
countdown -= now - timestamp;
if (countdown <= 0) countdown = 210000;
timestamp = now;
updateDisplay(dataset, "running");
}
function updateDisplay(dataset, label) {
dataset.state = label;
dataset.time = `(${new Date(countdown).toISOString().slice(14, 19)})`;
}
button::before {
content: attr(data-state);
}
button::after {
content: attr(data-time);
padding-left: 0.5em;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<button data-state="stopped" data-time="(03:30)"></button>

problem with clearInterval() in javascript

I made a simple little timer with a start, reset, plus a nonfunctional stop button. All the documentation that I have read on it makes it seem very simple so I have no idea what's going wrong.
the stop.onclick function is getting read, but it only works for a second before it gets overwritten by the setInterval function
ps- I intend to improve the accuracy so please no hints on how best to do that
const start = document.getElementById("button1")
const stop = document.getElementById("stop")
const reset = document.getElementById("reset")
var clock = start.onclick = function(){
let seconds = 1
let minutes = 0
setInterval(function() {
if (minutes == 0){
if (seconds < 10)
timer.innerHTML = '0:0' + seconds++;
else
timer.innerHTML = '0:' + seconds++;
if (seconds == 60){
minutes++
seconds = 0
}
}
else {
if (seconds < 10)
timer.innerHTML = minutes + ':0' + seconds++;
else
timer.innerHTML = minutes + ':' + seconds++;
if (seconds == 60){
minutes++
seconds = 0
}
}
}, 1000);
reset.onclick = function(){
seconds = 0
}
stop.onclick = function(){
let display = seconds
timer.innerHTML = display
clearInterval(clock)
// alert("You stopped the clock!")
}
}
```
The problem is that that is not how setInterval and clearInterval work. Specifically, you don't pass clearInterval the function that you have running at some interval to clear the interval. Instead, setInterval returns a reference to the process; you can then pass that reference to clearInterval to clear it. For instance:
const myIntervalProcess = setInterval(() => console.log('hi'), 1000);
setTimeout(() => clearInterval(myIntervalProcess), 5000);
What we see above is that we set a function that logs "hi" to the console every second. We save the reference returned from setInterval to a variable called myIntervalProcess. Then we set a timeout to pass myIntervalProcess to clearInterval after five seconds. If you run this you can see that "hi" will be logged to console exactly five times, after which point it will cease.
If we apply this fix to your code we get:
const start = document.getElementById("button1")
const stop = document.getElementById("stop")
const reset = document.getElementById("reset")
var clock = start.onclick = function(){
let seconds = 1
let minutes = 0
const clockProcess = setInterval(function() {
if (minutes == 0){
if (seconds < 10)
timer.innerHTML = '0:0' + seconds++;
else
timer.innerHTML = '0:' + seconds++;
if (seconds == 60){
minutes++
seconds = 0
}
}
else {
if (seconds < 10)
timer.innerHTML = minutes + ':0' + seconds++;
else
timer.innerHTML = minutes + ':' + seconds++;
if (seconds == 60){
minutes++
seconds = 0
}
}
}, 1000);
reset.onclick = function(){
seconds = 0
}
stop.onclick = function(){
let display = seconds
timer.innerHTML = display
clearInterval(clockProcess)
// alert("You stopped the clock!")
}
}
Also, for what it's worth, you may wish to use a linter on your code-- I see some missing semicolons and other errors/inconsistencies it would help you catch and resolve. Good luck!

javascript timer keeps reseting too soon (not working)

// This timer keeps reseting back to 2:00 after it reaches 1 minute. Also i do not get a notification that says times up at the right time. Can someone please correct the code. Also the stop/resume timer button also has to stay functional.
var isRunning = false;
var ticker; //this will hold our setTimeout
var seconds,
minutes;
function countdown(mins, secs) {
//i made these global, so we can restart the timer later
seconds = secs || 60; //if user put in a number of minutes, use that. Otherwise, use 60
minutes = mins;
console.log('time stuff',mins,secs,minutes,seconds)
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins - 1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if (seconds < 1 && minutes) {
//seconds reached 0, and still minutes left;
seconds=60;
minutes--;
}
if ((seconds > 0 || minutes > 0) && isRunning) {
ticker = setTimeout(tick, 1000);
} else if(isRunning){
console.log(seconds,minutes,isRunning)
alert('Time\'s up, brah!')
}
}
tick();
}
function timeToggle() {
isRunning = !isRunning; //if it's false, set it true. If it's true, set it false.
if (!isRunning) {
clearTimeout(ticker); //or whatever else you set the initial timeOut to.
} else {
//not running! and time is defined;
var sec = seconds||60;
console.log('def!',minutes, sec)
countdown(minutes, sec);
}
}
isRunning = true;
countdown(2);
<div id="timer">2:00</div>
<button onclick="timeToggle()">Stop time</button>
There is a small flaw in your logic.
During the countdown initialization your doing
seconds = secs || 60;
Which effectively add 60 seconds to the time you want if you don't initialize the seconds. see:
function countdownInit(mins, secs) {
seconds = secs || 60;
minutes = mins;
console.log(mins + 'min ' + seconds + 'sec');
}
countdownInit(1, 30) // ok
// 1min 30sec
countdownInit(1) // not ok
// 1min 60sec
// thats 2 minutes
The second issue here is that you use a var current_minutes that equals minutes - 1 to display the time. So you are not showing the real counter.
the fix is as follow:
function countdown(mins, secs) {
seconds = secs;
minutes = mins;
// if secs is 0 or uninitialized we set seconds to 60 and decrement the minutes
if(!secs) {
minutes--;
seconds = 60;
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
// we use minutes instead of current_minutes in order to show what's really in our variables
counter.innerHTML =
minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
// rest of code
}
// rest of code
}
I tried to keep as much as your code as possible.

Categories