Codepen
I am trying to simply get my play button to function but I don't know how. I got my pause button to work by adding clearInterval(timer) so I'm guessing I do the opposite of this?
I have tried adding countDown to to playTimer function and tick to the addEventListener but those don't work.
var startButton = document.getElementById("start");
var startSound = document.getElementById("audio");
var timerSound = document.getElementById("timer");
var counter = document.getElementById("counter");
var pausePlay = document.getElementsByClassName("pausePlay");
var pauseButton = document.getElementById("pause");
var playButton = document.getElementById('play');
var middleButtons = document.getElementsByClassName("middleButtons");
var fiveMin = document.getElementById("fiveMin");
var end = document.getElementById("endSess");
var redo = document.getElementById("redo");
function playAudio(){
startSound.play();
}
// Start button will disappear after click and countDown method will begin
function startTimer(){
startButton.style.display="none";
counter.style.display = "";
for (var i = 0; i < pausePlay.length; i++) {
pausePlay[i].style.display = "block";
}
countDown(10);
}
// function play(){
// }
function countDown(minutes){
var seconds = 60;
var mins = minutes;
function tick(){
var current_minutes = mins - 1;
seconds --;
counter.innerHTML = current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if(seconds > 0){
timer = setTimeout(tick, 1);
} else {
if(mins > 1){
countDown(mins - 1);
}
else if (mins && seconds === 0 ){
timerSound.play();
for (var i = 0; i < pausePlay.length; i++){
pausePlay[i].style.display = "none";
}
options();
}
}
}
tick();
}
// Pause timer
function pauseTimer(){
clearInterval(timer);
}
// Continue timer
function playTimer(){
countDown();
}
// Display buttons after timer is finished
function options(){
for(var i = 0; i < middleButtons.length; i++){
middleButtons[i].style.display = "block";
}
}
// Add five minutes to Counter as countdown
function fiveBreak (){
countDown(5);
}
// Restart counter to another 25 minutes
function restartTimer(){
countDown(25);
}
// Start from the beginning with the start timer
function endSess(){
for(var i = 0; i < middleButtons.length; i++){
middleButtons[i].style.display = "none";
counter.style.display = "none";
}
startButton.style.display = "";
}
startButton.addEventListener('click', startTimer, playAudio);
pauseButton.addEventListener('click', pauseTimer, playAudio );
playButton.addEventListener('click', playTimer, playAudio );
fiveMin.addEventListener('click', fiveBreak );
end.addEventListener('click', endSess);
redo.addEventListener('click', restartTimer);
here this is simple code to use for a basic countdown timer, I let you add your unnotified "audio" part
<h3 id="Count-Down">10</h3>
<select id="Count-times" >
<option value="20">20</option>
<option value="10" selected >10</option>
<option value="5">5</option>
</select>
<button id="bt-Start">start</button>
<button id="bt-Pause" disabled >pause</button>
<button id="bt-Clear" disabled >clear</button>
JS:
CountDown = {
CountDown : document.querySelector('#Count-Down'),
CountTime : document.querySelector('#Count-times'),
btStart : document.querySelector('#bt-Start'),
btPause : document.querySelector('#bt-Pause'),
btClear : document.querySelector('#bt-Clear'),
DownTime : 10 * 1000,
interV : 0,
Init()
{
// just for clean start on reload page
this.CountTime.value = 10;
// select time
this.CountTime.onchange =_=>{
this.DownTime = Number(this.CountTime.value) * 1000
this.CountDown.textContent = this.CountTime.value
}
// buttons click event
this.btStart.onclick =_=>{
this.CountDownTime();
this.CountTime.disabled = true;
this.btStart.disabled = true;
this.btPause.disabled = false;
this.btClear.disabled = false;
}
this.btPause.onclick =_=>{
clearInterval( this.interV );
this.btStart.disabled = false;
this.btPause.disabled = true;
}
this.btClear.onclick =_=>{
clearInterval( this.interV );
this.DownTime = 10 * 1000;
this.CountTime.value = 10;
this.CountDown.textContent = 10;
this.CountTime.disabled = false;
this.btStart.disabled = false;
this.btPause.disabled = true;
this.btClear.disabled = true;
}
}, /// Init
CountDownTime()
{
let D_End = new Date(Date.now() + this.DownTime );
this.interV = setInterval(_=>{
this.DownTime = D_End - (new Date(Date.now()));
if (this.DownTime > 0) {
// this.CountDown.textContent = Math.floor(this.DownTime / 1000) + '-' + (this.DownTime % 1000) ;
this.CountDown.textContent = (this.DownTime / 1000).toFixed(2); ;
}
else {
this.btClear.click();
}
}, 100);
}
}
CountDown.Init();
Related
let hour = 0;
let minute = 0;
let seconds = 0;
let pauseTime = null;
let start = [...document.cookie.matchAll(/([^;=]+)=([^;=]+)(;|$)/g)].filter(x => x[1].trim() == 'timer').map(x => Number(x[2].trim()))[0];
if(start != null) {
if(start > 0) start = new Date(start);
else if(start < 0) {
pauseTime = -start;
start = new Date(Date.now() + start); //+- = -
} else start = null;
} else start = null;
let intervalId = null;
function startTimer() {
let totalSeconds;
if(pauseTime) {
start = new Date(Date.now() - pauseTime);
totalSeconds = pauseTime;
return;
} else {
totalSeconds = Math.floor((Date.now() - start.getTime()) / 1000);
}
hour = Math.floor(totalSeconds /3600);
minute = Math.floor((totalSeconds - hour*3600)/60);
seconds = totalSeconds - (hour*3600 + minute*60);
document.getElementById("hour").innerHTML =hour;
document.getElementById("minute").innerHTML =minute;
document.getElementById("seconds").innerHTML =seconds;
}
if(start) intervalId = setInterval(startTimer, 1000);
document.getElementById('start-btn').addEventListener('click', () => {
if(pauseTime) {
pauseTime = null;
} else {
if(start) return;
start = new Date();
intervalId = setInterval(startTimer, 1000);
}
document.cookie = "timer=" + String(start.getTime());
})
document.getElementById('stop-btn').addEventListener('click', () => {
pauseTime = Date.now() - start.getTime();
document.cookie = "timer=" + String(-pauseTime);
alert("Timer is Currently paused. Press Okay to resume time.");
document.getElementById("start-btn").click();
});
document.getElementById('reset-btn').addEventListener('click', () => {
start = null;
document.cookie = "timer=null";
if(intervalId) clearInterval(intervalId);
document.getElementById("hour").innerHTML = '0';
document.getElementById("minute").innerHTML = '0';
document.getElementById("seconds").innerHTML = '0';
});
<button id="start-btn">Start</button>
<button id="stop-btn">Pause</button>
<button id="reset-btn">Reset</button>
I have a simple app that start, pauses and reset a timer when the appropriate button is clicked. What I am trying to do is create an alert box when the pause button is clicked and once someone clicks OK on the alert box, the timer starts again. I thought simply mimicking selecting the start button again would do this, but instead it starts the time like the pause never occurred. Any suggestion?
The goal I am trying to achieve is to get my timer to stop when all the questions of my quiz has been answered. I have 10 total questions. I have been able to get the timer to start. But getting ot to stop on the click of submit on the 10th question is something I can't figure out.
Let me know if you know what I am doing
StackOverflow said my code was too long... I added my code to codepen. I also included my JS on here.
// variables
var score = 0; //set score to 0
var total = 10; //total nmumber of questions
var point = 1; //points per correct answer
var highest = total * point;
//init
console.log('script js loaded')
function init() {
//set correct answers
sessionStorage.setItem('a1', "b");
sessionStorage.setItem('a2', "a");
sessionStorage.setItem('a3', "c");
sessionStorage.setItem('a4', "d");
sessionStorage.setItem('a5', "b");
sessionStorage.setItem('a6', "d");
sessionStorage.setItem('a7', "b");
sessionStorage.setItem('a8', "b");
sessionStorage.setItem('a9', "d");
sessionStorage.setItem('a10', "d");
}
// timer
// var i = 1;
// $("#startButton").click(function (e) {
// setInterval(function () {
// $("#stopWatch").html(i);
// i++;
// }, 1000);
// });
// $("#resetButton").click(function (e) {
// i = 0;
// });
//hide all questions to start
$(document).ready(function() {
$('.questionForm').hide();
//show question 1
$('#question1').show();
$('.questionForm #submit').click(function() {
//get data attribute
current = $(this).parents('form:first').data('question');
next = $(this).parents('form:first').data('question') + 1;
//hide all questions
$('.questionForm').hide();
//show next question in a cool way
$('#question' + next + '').fadeIn(400);
process('' + current + '');
return false;
});
});
//process answer function
function process(n) {
// get input value
var submitted = $('input[name=question' + n + ']:checked').val();
if (submitted == sessionStorage.getItem('a' + n + '')) {
score++;
}
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3> <button onclick="myScore()">Add Your Name To Scoreboard!</a>')
}
return false;
}
window.yourPoints = function() {
return n;
}
function myScore() {
var person = prompt("Please enter your name", "My First Name");
if (person != null) {
document.getElementById("myScore").innerHTML =
person + " " + score
}
}
// function showTime() {
// var d = new Date();
// document.getElementById("clock").innerHTML = d.toLocaleTimeString();
// }
// setInterval(showTime, 1000);
var x;
var startstop = 0;
window.onload = 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";
}
//adding an event listener
window.addEventListener('load', init, false);
https://codepen.io/rob-connolly/pen/xyJgwx
Any help would be appreciated.
its a pretty simple solution just call the stop function in the if condition of n == total
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3>
<button onclick="myScore()">Add Your Name To Scoreboard!</a>')
stop()
}
https://codepen.io/nony14/pen/VwYREgr
Try using clearInterval() to stop the timer.
https://codepen.io/thingevery/pen/dyPrgwz
I'm trying to make my countdown timer do the following 4 things
When 'start' is clicked, change button to 'stop'
When 'stop' is clicked, stop the timer
When timer is stopped, show 'start' button
When 'reset' is clicked, reset the timer
$(document).ready(function() {
var counter = 0;
var timeleft = 5;
function nf(num) {
var s = '0' + num;
return s.slice(-2);
}
function convertSeconds(s) {
var min = Math.floor(s / 60);
var sec = s % 60;
return nf(min, 2) + ' ' + nf(sec, 2);
}
function setup() {
var timer = document.getElementById("timer");
timer.innerHTML = (convertSeconds(timeleft - counter));
var interval = setInterval(timeIt, 1000);
function timeIt() {
counter++;
timer.innerHTML = (convertSeconds(timeleft - counter));
if (counter == timeleft) {
clearInterval(interval);
}
}
}
$("#timer-button").click(function() {
setup();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I recently needed something like this too. I ended up writing an ES6 class for that.
In my solution, I used Events to notify other components about the timer. Here is a fiddle in which I met your needs, but I left my EventManager() calls to show what I actually did.
The used EventManager is this one. The timer counts in 100ms steps by default, but you can adjust this by calling startTimer() with the interval of choice.
class Timer {
constructor(maxTime, startValue = 0) {
// Actual timer value 1/10s (100ms)
this.value = startValue;
// Maximum time of the timer in s
this.maxTime = maxTime * 10;
this.timerRunning = false;
}
/**
* Starts the timer. Increments the timer value every 100ms.
* #param {number} interval in ms
*/
startTimer(interval = 100) {
if (!this.timerRunning) {
let parent = this;
this.timerPointer = setInterval(function() {
if (parent.value < parent.maxTime) {
parent.value++;
//EventManager.fire('timerUpdated');
$("span").text(parent.value / 10 + "/" + parent.maxTime / 10);
} else {
parent.stopTimer();
//EventManager.fire('timeExceeded');
$("button").text("Start");
this.resetTimer();
$("span").text("Countdown over");
}
}, interval);
this.timerRunning = true;
}
}
// Stops the Timer.
stopTimer() {
clearInterval(this.timerPointer);
this.timerRunning = false;
}
// Resets the timer and stops it.
resetTimer() {
this.stopTimer();
this.value = 0;
$("span").text("0/" + this.maxTime/10);
//EventManager.fire('timerUpdated');
}
// Resets the timer and starts from the beginning.
restartTimer() {
this.resetTimer();
this.startTimer();
}
}
let timer = new Timer(6);
$("#start-stop").click(function() {
if (timer.timerRunning) {
timer.stopTimer();
$("#start-stop").text("Start");
} else {
timer.startTimer();
$("#start-stop").text("Stop");
}
});
$("#reset").click(function() {
timer.resetTimer();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start-stop">
Start
</button>
<button id="reset">
Reset
</button>
<span>Timer: </span>
const div = document.querySelector('div');
const btn = document.querySelector('#timerBtn');
const resetbtn = document.querySelector('#reset');
let startFlag = 0;
let count = 0;
let intervalId;
const ms = 1000;
div.textContent = count;
btn.addEventListener('click', function() {
startFlag = startFlag + 1;
if(startFlag%2 !== 0) { // Start button clicked;
btn.textContent = 'Stop';
startTimer();
} else {
btn.textContent = 'Start';
stopTimer();
}
});
resetbtn.addEventListener('click', function() {
count = 0;
div.textContent = count;
});
function startTimer() {
intervalId = setInterval(() => {
count = count + 1;
div.textContent = count;
}, 1000);
}
function stopTimer() {
clearInterval(intervalId);
}
<div></div>
<button id="timerBtn">Start</button>
<button id="reset">Reset</button>
Hi
I got countdown code
<script type="text/javascript">
window.onload = function() {
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
</script>
I want when the countdown end appear CAPTCHA or question if this right, then continue to link
try to put the countdown function here
window.onload = function() {
countDown('my_div1', //here// , 10);
}
Assume that your countdown coding is working fine and you have a div in which captcha is stored say div id = "captchadiv",
<script type="text/javascript">
window.onload = function() {
//////////////////////////////////////////////////////
set the visibility of the captcha hidden here.
//////////////////////////////////////////////////////
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
//////////////////////////////////////////////////////
set visibility of captchadiv to visibile.
//////////////////////////////////////////////////////
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
//////////////////////////////////////////////////////
add a function here to validate the captcha.
If validation succeeds, do success action.
If validation fails, set captcha visibility to hidden and again call the counttDown function.
//////////////////////////////////////////////////////
</script>
EDIT
Check this out. (Untested version)
<script type="text/javascript">
var mathenticate;
window.onload = function() {
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
mathenticate = {
bounds: {
lower: 5,
upper: 50
},
first: 0,
second: 0,
generate: function()
{
this.first = Math.floor(Math.random() * this.bounds.lower) + 1;
this.second = Math.floor(Math.random() * this.bounds.upper) + 1;
},
show: function()
{
return this.first + ' + ' + this.second;
},
solve: function()
{
return this.first + this.second;
}
};
mathenticate.generate();
var $auth = $('<input type="text" name="auth" />');
$auth
.attr('placeholder', mathenticate.show())
.insertAfter('input[name="name"]');
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
$('#form').on('submit', function(e){
e.preventDefault();
if( $auth.val() != mathenticate.solve() )
{
alert('wrong answer!');
// If you want to generate a new captcha, then
mathenticate.generate();
}else {
document.location.href = 'http://www.overdir.com';
}
});
</script>
I tried using this JavaScript countdown timer on my page but the timer won't start.
What am I doing wrongly?
var CountdownID = null;
var start_msecond = 9;
var start_sec = 120;
window.onload = countDown(start_msecond, start_sec, "timerID");
function countDown(pmsecond, psecond, timerID) {
var msecond = ((pmsecond < 1) ? "" : "") + pmsecond;
var second = ((psecond < 9) ? "0": "") + psecond;
document.getElementById(timerID).innerHTML = second + "." + msecond;
if (pmsecond == 0 && (psecond-1) < 0) { //Recurse timer
clearTimeout(CountdownID);
var command = "countDown("+start_msecond+", "+start_sec+", '"+timerID+"')";
CountdownID = window.setTimeout(command, 100);
alert("Time is Up! Enter your PIN now to subscribe!");
}
else { //Decrease time by one second
--pmsecond;
if (pmsecond == 0) {
pmsecond=start_msecond;
--psecond;
}
if (psecond == 0) {
psecond=start_sec;
}
var command = "countDown("+pmsecond+", "+psecond+", '"+timerID+"')";
CountdownID = window.setTimeout(command, 100);
}
}
<span style="color:red" name="timerID" id="timerID">91.6</span>
here is what you need to do first
window.onload = countDown(start_msecond, start_sec, "timerID");
should be
window.onload = function () {
countDown(start_msecond, start_sec, "timerID");
}
also you should avoid using a string in your setTimeout function:
CountdownID = window.setTimeout(function () {
countDown(pmsecond,psecond,"timerID");
}, 100);
See here http://jsbin.com/ifiyad/2/edit