I just started teaching myself front end coding and was wondering how to make a timer that when ends makes a button go to a random position across the screen. Here's the code I wrote(stole).
Here's the code I wrote(stole) but the timer doesn't restart when it ends. I need it to move the button after resetting the timer.
var h3 = document.getElementsByTagName("h3");
h3[0].innerHTML = "Countdown Timer With JS";
var sec = 5,
countDiv = document.getElementById("timer"),
secpass,
countDown = setInterval(function () {
"use strict";
secpass();
}, 1000);
function secpass() {
"use strict";
var min = Math.floor(sec / 60),
remSec = sec % 60;
if (remSec < 10) {
remSec = "0" + remSec;
}
if (min < 10) {
min = "0" + min;
}
countDiv.innerHTML = min + ":" + remSec;
if (sec > 0) {
sec = sec - 1;
} else {
clearInterval(countDown);
var b = document.getElementById("thing");
var i = Math.floor(Math.random() * 800) + 1;
var j = Math.floor(Math.random() * 600) + 1;
b.style.left = i + "px";
b.style.top = j + "px";
}
};
Related
I have following script:
document.getElementById("timer").innerHTML = 0 + ":" + 10;
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 class="sale_content">
СКИДКА АКТИВНА ЕЩЁ: <span id="timer"></span>
</div>
All works great, but when timer expires it just shows "0:00"
How can I add expiration message inside ?
Thank you!
You can add your message expiry message, inside the minute expiry if block if (m<0){} before the return statement. I added the solution to your code below for reference
<div class="sale_content">
СКИДКА АКТИВНА ЕЩЁ: <span id="timer"></span>
</div>
<script>
document.getElementById('timer').innerHTML =
0 + ":" + 3;
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){
document.getElementById('timer').innerHTML = "Timer expired."
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;
}
startTimer();
</script>
</body>
</html>
the problem is that you want to console.log(m) which is just 0:00. I've changed a bit of your code so instead of m it logs n which is: n = m + ":" + s;
<div class="sale_content">
СКИДКА АКТИВНА ЕЩЁ: <span id="timer"></span>
</div>
<script>
document.getElementById('timer').innerHTML =
0 + ":" + 10;
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 =
n = m + ":" + s;
console.log(n)
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>
try it like this
var timeleft = 11;
var downloadTimer = setInterval(function(){
if(timeleft <= 0){
clearInterval(downloadTimer);
alert("Timer Expired!")
return;
}
document.getElementById("progressBar").value = timeleft - 1;
document.getElementById("timer").innerHTML = "0:"+(timeleft - 1);
timeleft -= 1;
}, 1000);
<div class="sale_content">
СКИДКА АКТИВНА ЕЩЁ: <span id="timer"></span>
</div>
<progress value="0" max="10" id="progressBar"></progress>
I'm building a memory card game.
I want to show the time from the moment the user pressed on the first card till they win.
i dont understand how to make the stopwatch to continue counting while the player plays without it getting stuck or not refreshing the display enough.
HTML:
<h4 class="stopwatch">00:00:00</h4>
JavaScript:
while (TOTAL_COUPLES_COUNT !== flippedCouplesCount) {
sec++;
if (sec == 60) {
min = min + 1;
sec = 0;
}
if (min == 60) {
hr = hr + 1;
min = 0;
sec = 0;
}
elStopwatch.innerHTML = hr + ":" + min + ":" + sec;
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>
Hi there I have a stopwatch embedded in my website, however I have a problem. When the seconds reach 60 therefore 1 minute they should reset to 00. However in this case while the minute will increase every 60 seconds the seconds will not reset to zero. Here is my code
<div id="output">00:00:00</div>
<button id="startPause" onclick="startPause()">Start</button>
<button onclick="reset()">Reset</button>
<script type="text/javascript">
var time = 0;
var running = 0;
function startPause() {
if (running == 0) {
running = 1;
increment();
document.getElementById('startPause').innerHTML = 'Pause';
} else {
running = 0;
document.getElementById('startPause').innerHTML = 'Resume';
}
}
function reset() {
running = 0;
time = 0;
document.getElementById('output').innerHTML = '00:00:00';
document.getElementById('startPause').innerHTML = 'Start';
}
function increment() {
if (running == 1) {
setTimeout(function() {
time++;
var mins = Math.floor(time / 10 / 60);
if (mins <= 9) {
mins = '0' + mins;
}
var secs = Math.floor(time / 10);
if (secs <= 9) {
secs = '0' + secs;
}
var tenths = Math.floor(time % 10);
if (tenths <= 9) {
tenths = '0' + tenths;
}
document.getElementById('output').innerHTML =
mins + ':' + secs + ':' + tenths;
increment();
}, 100);
}
}
</script>
Any help much appreciated
You can use that code
<div id="output">00:00:00</div>
<button id="startPause" onclick="startPause()">Start</button>
<button onclick="reset()">Reset</button>
<script type="text/javascript">
var time = 0;
var running = 0;
function startPause() {
if (running == 0) {
running = 1;
increment();
document.getElementById('startPause').innerHTML = 'Pause';
} else {
running = 0;
document.getElementById('startPause').innerHTML = 'Resume';
}
}
function reset() {
running = 0;
time = 0;
document.getElementById('output').innerHTML = '00:00:00';
document.getElementById('startPause').innerHTML = 'Start';
}
function increment() {
if (running == 1) {
setTimeout(function() {
time++;
var mins = Math.floor(time / 10 / 60);
if (mins <= 9) {
mins = '0' + mins;
}
var secs = Math.floor(time / 10);
if(secs >= 60)
{
secs = secs - ( mins * 60 );
}
if ((secs).toString().length === 1) {
secs = '0' + secs;
}
var tenths = Math.floor(time % 10);
if ((tenths).toString().length === 1) {
tenths = '0' + tenths;
}
document.getElementById('output').innerHTML =
mins + ':' + secs + ':' + tenths;
increment();
}, 100);
}
}
</script>
Just include a modulo by 60 to line number 36 to properly reset seconds to 0 (line commented to highlight):
<div id="output">00:00:00</div>
<button id="startPause" onclick="startPause()">Start</button>
<button onclick="reset()">Reset</button>
<script type="text/javascript">
var time = 0;
var running = 0;
function startPause() {
if (running == 0) {
running = 1;
increment();
document.getElementById('startPause').innerHTML = 'Pause';
} else {
running = 0;
document.getElementById('startPause').innerHTML = 'Resume';
}
}
function reset() {
running = 0;
time = 0;
document.getElementById('output').innerHTML = '00:00:00';
document.getElementById('startPause').innerHTML = 'Start';
}
function increment() {
if (running == 1) {
setTimeout(function() {
time++;
var mins = Math.floor(time / 10 / 60);
if (mins <= 9) {
mins = '0' + mins;
}
var secs = Math.floor(time / 10) % 60; // <-- see here for change
if (secs <= 9) {
secs = '0' + secs;
}
var tenths = Math.floor(time % 10);
if (tenths <= 9) {
tenths = '0' + tenths;
}
document.getElementById('output').innerHTML =
mins + ':' + secs + ':' + tenths;
increment();
}, 100);
}
}
</script>
I am making a Pomodoro clock. I took a clock object, added start, pause, resume functions. To run the clock repeatedly in the start function I added two variable s and b to keep the original time of session and break. So, in the pause function when I am deleting the timer the original time of session and break is getting deleted. so
resume function clock is staring from the beginning. Now, how to write the pause function in the right way to make the resume?
This is JSfiddle link. http://jsfiddle.net/sajibBD/f18nh323/3/
Thanks in advance!
var Clock = {
sessionSeconds: 0,
breakSeconds: 0,
start: function () {
var self = this;
var s = this.sessionSeconds + 1;
var b = this.breakSeconds + 1;
this.interval = setInterval(function () {
if (s > 0) {
s -= 1;
$('#state').text('Session');
$("#min").text(Math.floor(s / 60 % 60));
$("#sec").text(parseInt(s % 60));
} else if (b > 0) {
b -= 1;
$('#state').text('Break');
$("#min").text(Math.floor(b / 60 % 60));
$("#sec").text(parseInt(b % 60));
} else if (b === 0) {
s = self.sessionSeconds + 1;
b = self.breakSeconds + 1;
}
var min = $("#min").text();
var sec = $("#sec").text();
if (min.length === 1) {
$("#min").text('0' + min);
}
if (sec.length === 1) {
$("#sec").text('0' + sec);
}
}, 1000)
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
if (!this.interval) this.start();
},
}
Try this one:
http://jsfiddle.net/f18nh323/5/
var Clock = {
sessionSeconds: 0,
breakSeconds: 0,
start: function () {
var self = this;
var s = this.sessionSeconds + 1;
var b = this.breakSeconds + 1;
this.interval = setInterval(function () {
if (s > 0) {
s -= 1;
$('#state').text('Session');
$("#min").text(Math.floor(s / 60 % 60));
$("#sec").text(parseInt(s % 60));
} else if (b > 0) {
b -= 1;
$('#state').text('Break');
$("#min").text(Math.floor(b / 60 % 60));
$("#sec").text(parseInt(b % 60));
} else if (b === 0) {
s = self.sessionSeconds + 1;
b = self.breakSeconds + 1;
}
self.sessionSeconds = s;
var min = $("#min").text();
var sec = $("#sec").text();
if (min.length === 1) {
$("#min").text('0' + min);
}
if (sec.length === 1) {
$("#sec").text('0' + sec);
}
}, 1000)
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
if (!this.interval) this.start();
},
}
I was looking for a jquery countup timer that was based on the time of day, and I was struggling to find one so here I just wrote my own. Here it is for anyone who's looking for one.
The objective is to take the time of day, calculate a percentage through the day of that current time, multiply it by an objective sum and start adding to create a realistic timing scenario. My timers are firing to create the simulation of an unsteady data flow, but you can change it to a steady increase easily.
The element with the number is #counter, and the objective total is the 3.5mm.
var currentNumber;
$(document).ready(function (e) {
var currDate = new Date();
var mins = currDate.getMinutes();
var hours = currDate.getHours();
var seconds = currDate.getSeconds();
var combined = (hours * 60 * 60) + (mins * 60) + seconds;
var percentage = (combined / 90000);
var startingPoint = Math.round(3500000 * percentage);
currentNumber = startingPoint;
$('#counter').html(formatNumber(startingPoint));
setTimeout(function () {
updateNumber(currentNumber)
}, 100);
});
function updateNumber(startingPoint) {
if (startingPoint % 58 === 0) {
startingPoint += 5;
currentNumber = startingPoint;
$('#counter').html(formatNumber(currentNumber));
setTimeout(function () {
updateNumber(currentNumber)
}, 850);
} else if (startingPoint % 22 === 0) {
startingPoint += 4;
currentNumber = startingPoint;
$('#counter').html(formatNumber(currentNumber));
setTimeout(function () {
updateNumber(currentNumber)
}, 500);
} else if (startingPoint % 6 === 0) {
startingPoint += 1;
currentNumber = startingPoint;
$('#counter').html(formatNumber(currentNumber));
setTimeout(function () {
updateNumber(currentNumber)
}, 75);
} else {
startingPoint += 5;
currentNumber = startingPoint;
$('#counter').html(formatNumber(currentNumber));
setTimeout(function () {
updateNumber(currentNumber)
}, 250);
}
}
function formatNumber(number) {
return addCommas((number).toFixed(0));
}
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}