JavaScript countdown timer not starting - javascript

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

Related

How do I get my timer to stop, when my 10th and last question has been answered?

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

How to stop javascript counter at specific number

I have this javascript code for tampermonkey that works on Amazon. What it does is just counts up your gift card balance and makes it look like I am getting money. I want to know if it is possible to make it stop at a specific number.
var oof = document.getElementById("gc-ui-balance-gc-balance-value");
var lastCount = localStorage.getItem("lastCount");
oof.innerText = '$' + lastCount || "$10000";
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(localStorage.getItem("lastCount")) || 10000;
setInterval(function () {
var nextCount = current++;
localStorage.setItem("lastCount", nextCount);
obj.innerText = '$' + nextCount;
}, 0.1);
}
animateValue('gc-ui-balance-gc-balance-value')
Use clearInterval inside your setInterval callback so each time the callback is called, you can check if the new count has reached your threshold and clear the timer if it does.
If you check the value outside of the callback, the logic won't be called at each count increment.
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(localStorage.getItem("lastCount")) || 10000;
var interval = null;
var maxCount = 1000;
var callback = function() {
var nextCount = current++;
if (nextCount === maxCount) {
clearInterval(interval);
}
localStorage.setItem("lastCount", nextCount);
obj.innerText = '$' + nextCount;
}
interval = setInterval(callback, 0.1);
}
Here is a demo:
let current = 0;
let interval = null;
const callback = () => {
let nextCount = current++;
console.log(nextCount);
if (nextCount === 5) {
clearInterval(interval);
}
}
interval = setInterval(callback, 100);
May be by clearing the interval when current reaches to a specific value like this
function animateValue(id) {
// rest of the code
let interval = setInterval(function() {
var nextCount = current++;
localStorage.setItem("lastCount", nextCount);
obj.innerText = '$' + nextCount;
}, 0.1);
if (current === requiredVal) {
clearInterval(interval)
}
return current;
}

Coundown cokie set up

I cant figuret how set cookie for my countdownt timeer, that if i refresh page it vill not disapear but vill counting.
i be glad if eny can help. i use jquery 2.1.4 and this java countdown script, but when i refresh page all my coundown timers are lost!
/**
* Created by op on 18.07.2015.
*/
function leadZero (n)
{
n = parseInt(n);
return (n < 10 ? '0' : '') + n;
}
function startTimer(timer_id) {
var timer = $(timer_id);
var time = timer.html();
var arr = time.split(":");
var h = arr[0];
h = h.split(" / ");
h = h[1];
var m = arr[1];
var s = arr[2];
if (s == 0)
{
if (m == 0)
{
if (h == 0)
{
timer.html('')
return;
}
h--;
m = 60;
}
m--;
s = 59;
}
else
{
s--;
}
timer.html(' / '+leadZero(h)+":"+leadZero(m)+":"+leadZero(s));
setTimeout(function(){startTimer(timer_id)}, 1000);
}
function timer (name, time)
{
var timer_name = name;
var timer = $(timer_name);
var time_left = time;
timer.html(' / '+ time);
startTimer(timer_name);
}
$(document).ready(function(){
$('.fid').click(function (e)
{
var timer_name = '.timer_'+$(this).data('fid');
var timer = $(timer_name);
if (timer.html() == '')
{
var time_left = timer.data('timer');
var hours = leadZero(Math.floor(time_left / 60));
var minutes = leadZero(time_left % 60);
var seconds = '00';
timer.html(' / '+hours+':'+minutes+':'+seconds);
startTimer(timer_name);
}
});
$.each($('.tab'), function () {
$(this).click(function () {
$.each($('.tab'), function() {
$(this).removeClass('active');
});
$(this).addClass('active');
$('.list').hide();
$('#content-'+$(this).attr('id')).show();
});
});
if (window.location.hash != '')
{
var tab = window.location.hash.split('-');
tab = tab[0];
$(tab).click();
}
console.log(window.location.hash)
});
It would help if you actually set a cookie.
Setting the cookie would go like:
document.cookie="timer=" + time;
And then call it at the beginning of your code
var time = getCookie("timer");
The getCookie() function is outlined in that link, as well as a base knowledge about them.

Cant a function be implemented into while loop?

function start() {
var work = document.getElementById("work").value;
var rest = document.getElementById("rest").value;
var rounds = document.getElementById("rounds");
var timer = document.getElementById("timer");
function countdown() {
var roundsValue = rounds.value;
while (roundsValue > 0) {
var worktime = setInterval(function () {
timer.value = work + "sec";
work = work - 1;
if (work === 0) {
clearInterval(worktime);
}
}, 1000);
var resttime = setInterval(function(){
timer.value = rest + "sec";
rest = rest-1;
if(rest === 0){
clearInterval(resttime);
}
}, 1000);
roundsValue = roundsValue-1;
}
}
}
I am working on my javascript progress right now and I came here with this problem. I want to repeat the same amount of work time and rest time as rounds are but it doesnt work like this and I cant help myself. For example: 8 rounds of 10 seconds of work and then 5seconds of rest. It maybe doesnt work because function cant be implemented into a WHILE loop.
fiddle: http://jsfiddle.net/shhyq02e/4/
Here is a quick fix, may not be the best way to go about it but will get what to do.
http://jsfiddle.net/sahilbatla/shhyq02e/6/
function start() {
var rounds = document.getElementById("rounds");
var timer = document.getElementById("timer");
var roundsValue = parseInt(rounds.value);
(function countdown() {
var work = document.getElementById("work").value;
var rest = document.getElementById("rest").value;
if (roundsValue > 0) {
var worktime = setInterval(function () {
timer.value = work + "sec(work)";
work = work - 1;
if (work === 0) {
clearInterval(worktime);
var resttime = setInterval(function() {
timer.value = rest + "sec(rest)";
rest = rest - 1;
if (rest === 0) {
clearInterval(resttime);
--roundsValue;
countdown();
}
}, 1000);
}
}, 1000);
}
})();
}

How to pause and resume a javascript timer [duplicate]

This question already has an answer here:
how to pause timer or freeze it and resume -> javascript
(1 answer)
Closed 9 years ago.
I have this timer which works fine, but i need to be able to pause and resume it after that. i would appreciate it if someone could help me.
<html>
<head>
<script>
function startTimer(m,s)
{
document.getElementById('timer').innerHTML= m+":"+s;
if (s==0)
{
if (m == 0)
{
return;
}
else if (m != 0)
{
m = m-1;
s = 60;
}
}
s = s-1;
t=setTimeout(function(){startTimer(m,s)},1000);
}
</script>
</head>
<body>
<button onClick = "startTimer(5,0)">Start</button>
<p id = "timer">00:00</p>
</body>
</html>
I simply can't stand to see setTimeout(...,1000) and expecting it to be exactly 1,000 milliseconds. Newsflash: it's not. In fact, depending on your system it could be anywhere between 992 and 1008, and that difference will add up.
I'm going to show you a pausable timer with delta timing to ensure accuracy. The only way for this to not be accurate is if you change your computer's clock in the middle of it.
function startTimer(seconds, container, oncomplete) {
var startTime, timer, obj, ms = seconds*1000,
display = document.getElementById(container);
obj = {};
obj.resume = function() {
startTime = new Date().getTime();
timer = setInterval(obj.step,250); // adjust this number to affect granularity
// lower numbers are more accurate, but more CPU-expensive
};
obj.pause = function() {
ms = obj.step();
clearInterval(timer);
};
obj.step = function() {
var now = Math.max(0,ms-(new Date().getTime()-startTime)),
m = Math.floor(now/60000), s = Math.floor(now/1000)%60;
s = (s < 10 ? "0" : "")+s;
display.innerHTML = m+":"+s;
if( now == 0) {
clearInterval(timer);
obj.resume = function() {};
if( oncomplete) oncomplete();
}
return now;
};
obj.resume();
return obj;
}
And use this to start/pause/resume:
// start:
var timer = startTimer(5*60, "timer", function() {alert("Done!");});
// pause:
timer.pause();
// resume:
timer.resume();
<p id="timer">00:00</p>
<button id="start">Start</button>
<button id="pause">Pause</button>
<button id="resume">Resume</button>
var timer = document.getElementById("timer");
var start = document.getElementById("start");
var pause = document.getElementById("pause");
var resume = document.getElementById("resume");
var id;
var value = "00:00";
function startTimer(m, s) {
timer.textContent = m + ":" + s;
if (s == 0) {
if (m == 0) {
return;
} else if (m != 0) {
m = m - 1;
s = 60;
}
}
s = s - 1;
id = setTimeout(function () {
startTimer(m, s)
}, 1000);
}
function pauseTimer() {
value = timer.textContent;
clearTimeout(id);
}
function resumeTimer() {
var t = value.split(":");
startTimer(parseInt(t[0], 10), parseInt(t[1], 10));
}
start.addEventListener("click", function () {
startTimer(5, 0);
}, false);
pause.addEventListener("click", pauseTimer, false);
resume.addEventListener("click", resumeTimer, false);
on jsfiddle
There are a whole load of improvements that could be made but I'm sticking with the code that the OP posted for the OP's comprehension.
Here is an extended version to give you further ideas on jsfiddle

Categories

Resources