How to make Javascript Count Up timer work - javascript

I am trying to implement a simple count up timer using Javascript and show the timer in the HTML page. This is my code:
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;
}
}
HTML:
<label id="minutes">00</label>
<label id="colon">:</label>
<label id="seconds">00</label>
But the timer is not working in the HTML. It stays at 00:00

Make sure the script is at the bottom on the body tag

The code you posted works exactly as you describe.
Check this fiddle, I just copy pasted it.
.

The code you mentioned is working perfectly fine in the snippets.

Related

How can I modify a variable on another site?

My son is doing times tables practice on this page, a timed test in which he gets 10 seconds for each sum.
https://www.timestables.com/speed-test/ - this is not my site or code, I have no direct control over the source code.
I want to give him a little more time per sum but I cannot find a way to modify the relevant code and make it work with 20 seconds instead of 10.
It looks to me like the relevant variable is maxTime (milliseconds) in this function, but nothing I do using the Chrome Developer Tools will modify this in a live running page to give 20 seconds instead of 10.
function startSom(){
vraagnr = vraagnr + 1;
if(vraagnr <= totaalSommen)
{
bezig = true;
$('#pbar_innerdiv').stop();
$('#pbar_innerdiv').css("width","100%");
$('#pbar_innerdiv').css("backgroundColor","#33BF00");
$('#pbar_innerdiv').css("borderColor","#33BF00");
if(mobiel){
$("#antwVak").html("");
}
else{
$("#antwoordI").val("");
$("#antwoordI").focus();
}
$('#pbar_innerdiv').stop();
start = new Date();
maxTime = 10000;
timeoutVal = Math.floor(maxTime/100);
var somT = sommen[vraagnr-1].split(",");
$('#somVak').html(somT[1]+"×"+somT[0]+"=");
$('#voortgangVak').html("Question "+vraagnr+" / "+totaalSommen+"<br />"+ punten + " points");
animateUpdate();
started = false;
}
else
{
showEindScherm();
}
}
Can anyone suggest what to do please?
You can copy the entire method, pase it into chrome devtools and change
function startSom() {
to
window.startSom = function() {
And obviously change your time from 10000 to 20000. This changes the amount of time it allows you to answer, but not the moving progress bar which will still only take 10 seconds.
Please paste this:
window.startSom = function(){
vraagnr = vraagnr + 1;
if(vraagnr <= totaalSommen)
{
bezig = true;
$('#pbar_innerdiv').stop();
$('#pbar_innerdiv').css("width","100%");
$('#pbar_innerdiv').css("backgroundColor","#33BF00");
$('#pbar_innerdiv').css("borderColor","#33BF00");
if(mobiel){
$("#antwVak").html("");
}
else{
$("#antwoordI").val("");
$("#antwoordI").focus();
}
$('#pbar_innerdiv').stop();
start = new Date();
maxTime = 20000;
timeoutVal = Math.floor(maxTime/100);
var somT = sommen[vraagnr-1].split(",");
$('#somVak').html(somT[1]+"×"+somT[0]+"=");
$('#voortgangVak').html("Question "+vraagnr+" / "+totaalSommen+"<br />"+ punten + " points");
animateUpdate();
started = false;
}
else
{
showEindScherm();
}
}
Here:
And if you want to make the progress bar following the new max Time, also paste this:
window.animateUpdate = function() {
if(bezig)
{
var now = new Date();
var timeDiff = now.getTime() - start.getTime();
if(!started){
$('#pbar_innerdiv').css("width", (100) + "%");
$('#pbar_innerdiv').animate({width: 0 + "%"},20000);
started = true;
}
perc = Math.round((timeDiff/maxTime)*100);
console.log(perc);
if(perc == 33)
{
$('#pbar_innerdiv').css("backgroundColor", "#FF9500");
$('#pbar_innerdiv').css("borderColor", "#FF9500");
}
if(perc== 66)
{
$('#pbar_innerdiv').css("backgroundColor", "#FF0000");
$('#pbar_innerdiv').css("borderColor", "#FF0000");
}
if (perc <= 100) {
//updateProgress(perc);
setTimeout(animateUpdate, timeoutVal);
}
else
{
bezig = false;
showTeLaat();
//alert("tijd is om");
}
}
}
There is a possibility to change files persistently in chrome devtools: Overrides.
If the script is in a seperate file you can change the maxTime directly there or if it is in a file, which needs to be reloaded you can edit any other .js and add an eventlistener there to change the startSom method on page load.

Timer doesn't start running

I tried to make a normal Timer in Javascript and started coding something with help of some Tutorials.
I did it the same way as in the tutorial but my timer actually doesn't start running, and i don't know why.
Here is my Code:
var time = 0;
var running = 0;
function startPause() {
if(running == 0){
running = 1;
increment();
}
else{
running = 0;
}
}
function reset(){
running = 0;
time = 0;
document.getElementById("startPause").innerHTML = "Start";
}
function increment() {
if(running == 1){
setTimeout(function(){
time++;
var mins = Math.floor(time / 10 / 60);
var secs = Math.floor(time / 10);
var tenths = time % 10;
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + tenths;
}, 100);
}
}
</script>
i also made a fiddle you can check out here: https://jsfiddle.net/adamswebspace/5p1qgsz9/
what is wrong with my code?
I cleared a bit your code, and used setInterval instead of setTimeOut;
note that you have to use clearInterval in order to stop the timer
var time = 0;
var running = 0;
var timer = null;
function increment() {
time++;
var mins = Math.floor(time / 10 / 60);
var secs = Math.floor(time / 10);
var tenths = time % 10;
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + tenths;
}
function startPause() {
if (running === 0) {
running = 1;
timer = setInterval(increment, 1000);
} else {
running = 0;
clearInterval(timer);
}
}
function reset() {
running = 0;
time = 0;
document.getElementById("startPause").innerHTML = "Start";
}
you have to bind the function like the following
var vm = this;
vm.startPause = function startPause() {
if (running == 0) {
running = 1;
vm.increment();
} else {
running = 0;
}
}
https://jsfiddle.net/f7hmbox7/
In order for onclick to find the function in your code. It must be supplied in a <script> tag for JSFiddle.
You can just add
<script>
/** JS Here */
</script>
and it will work.
Keep in mind that all the errors coming from JS are showed in the console of your browser inspector.
https://jsfiddle.net/dzskncpw/

Countdown timer working stop on chrome extensions.

I think that I will build chrome extensions to count down.
In case of the present code, if popup.html is closed, processing will be completed compulsorily.
In this case, is it better to write setInterval to background.js?
Moreover, I want you to teach whether what I should do concrete.
background.js
var num = window.localStorage.setItem("minite_num", 20);
default_count = num*60;
function count_start() {
count = default_count;
chrome.browserAction.setIcon({
path: {
"19": "img/icon_count19.png",
"38": "img/icon_count38.png"
}
});
}
function count_down() {
count--;
if (count <= 0) {
page_change();
count_stop();
}
}
popup.js
var bg = chrome.extension.getBackgroundPage();
var num = bg.num;
var start_btn = document.count_timer.start_btn;
var count_time = document.getElementById("counter");
document.addEventListener('DOMContentLoaded', function () {
load();
start_btn.addEventListener('click', start_display);
});
function timer_reset() {
timerID = 0;
}
function count_format(num) {
var tm,ts;
tm = Math.floor(num / 60); //分
ts = num % 60; //秒
if (ts < 10) ts = "0" + ts;
return tm + ":" + ts;
}
function load(){
display_num = bg.count_format(bg.default_count);
bg.timer_reset();
start_btn.disabled = false;
count_time.innerHTML = display_num;
}
function start_display() {
start_btn.disabled = true;
bg.count_start();
timerID = setInterval(function() {bg.count_down();count_time.innerHTML = bg.count;}, 1000);
}
popup.html
<form name="count_timer" class="count_timer">
<div id="counter" class="counter"></div>
<input type="button" name="start_btn" value="START">
</form>
Thanks.
use chrome storage / localStorage to remember your target time.
Use an interval from the popup to update your calculations. First time, the popup needs to read from storage and determine where the countdown is at.
Nothing needs to be done from background, unless you want to separate logic (as in MVC), then maybe do all storage stuff from background, and ask for it with messaging.
I have a published open-source chrome extension (plus for trello) with a count(up) timer feature that does something similar.

Pause / Resume jQuery Countdown Timer

I'm trying to make a countdown timer that can be paused with a single HTML5 button tag using a JS onClick() event, or more preferably, using jQuery with something like $("#pause_resume").off('click').on('click', firstClick)in conjunction with another function. Logically, I would assume the task would require getting the current values of both $.min and $.sec and then setting these values, while switching functions, until the "resume" button is pressed again. But I honestly have no idea how to go about doing this. I've looked at other code on this site and others, but what I saw was heavily deprecated and not in line with my project plan. Any insight is appreciated.
HTML:
<p class="timer">
<span class="min"></span>:<span class="sec"></span>/
<span class="fullTime">1:30</span>
</p>
JavaScript:
<script type="text/javascript">
var timer = $('.timer');
var leadingZero = function(n) {
if (n < 10 && n >= 0)
return '0' + n;
else
return n;
};
var minutes = 1;
var seconds = 30;
setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (seconds == 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
m.text(minutes);
s.text(leadingZero(seconds));
}, 1000);
</script>
Well, I think this is what you want. http://jsfiddle.net/joey6978/67sR2/3/
I added a button that toggles a boolean on click to determine whether to set your function in the interval or to clear the interval.
var clicked=true;
var counter;
$('button').click(function(){
if(clicked){
counter=setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (seconds === 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
m.text(minutes);
s.text(leadingZero(seconds));
}, 1000);
}
else{
clearInterval(counter);
}
clicked=!clicked;
});

jquery: stopwatch

I'm using the stopwatch code I found here:
http://www.kellishaver.com/projects/stopwatch/
(function($) {
$.fn.stopwatch = function() {
var clock = this;
var timer = 0;
clock.addClass('stopwatch');
//console.log(clock);
// This is bit messy, but IE is a crybaby and must be coddled.
clock.html('<div class="display"><span class="hr">00</span>:<span class="min">00</span>:<span class="sec">00</span></div>');
clock.append('<input type="button" class="start" value="Start" />');
clock.append('<input type="button" class="stop" value="Stop" />');
clock.append('<input type="button" class="reset" value="Reset" />');
//console.log(clock.html());
// We have to do some searching, so we'll do it here, so we only have to do it once.
var h = clock.find('.hr');
var m = clock.find('.min');
var s = clock.find('.sec');
var start = clock.find('.start');
var stop = clock.find('.stop');
var reset = clock.find('.reset');
stop.hide();
start.bind('click', function() {
timer = setInterval(do_time, 1000);
stop.show();
start.hide();
});
stop.bind('click', function() {
clearInterval(timer);
timer = 0;
start.show();
stop.hide();
});
reset.bind('click', function() {
clearInterval(timer);
timer = 0;
h.html("00");
m.html("00");
s.html("00");
stop.hide();
start.show();
});
function do_time() {
// parseInt() doesn't work here...
hour = parseFloat(h.text());
minute = parseFloat(m.text());
second = parseFloat(s.text());
second++;
if(second > 59) {
second = 0;
minute = minute + 1;
}
if(minute > 59) {
minute = 0;
hour = hour + 1;
}
h.html("0".substring(hour >= 10) + hour);
m.html("0".substring(minute >= 10) + minute);
s.html("0".substring(second >= 10) + second);
}
};
})(jQuery);
And I use it like this:
<script type="text/javascript">
$('#clock1').stopwatch();
</script>
It works fine and I can stop it using the stop button. However I would like to be able to stop it programatically using javascript. Something like this:
<script type="text/javascript">
$('#clock1').stop();
</script>
I created the stop function but I cannot access the timer var defined in stopwatch(). How can I do it?
How about:
$('#clock1').find('.stop').trigger('click');
You can add a small API to the code and attach it using $.data:
var api = {
stop: function() {
stop.click(); // this should probably be improved, but you get the idea
}
};
$(clock).data('stopwatch', api);
Then use:
$('#clock1').data('stopwatch').stop();
You can also add the reset and start functions to the API using the same logic. A good thing here is that you can improve the execution code on a coffee break later without changing the way external programs uses the API.

Categories