Show a countdowntimer-script with DOM - javascript

I'm fairly new to DOM and the whole HTML and PHP Stuff so I'm seeking some information on how to do this. What I have until now is a Javascript. Now I want/have to use DOM to show this script. (FYI: I'm implementing something for Moodle and this has be done like this)
What I have found out about DOM is that I can change values of different Nodes. The problem I've found myself in is that all the examples I found were like. Click on a button and something happens. That's ok but now I want my script to run every second so I can the person who needs it can see that the time is running down.
I hope I gave you enough information and I hope you can help me. Thank you for trying to help me.
var running = false
var endTime = null
var timerID = null
// totalMinutes the amount of minutes is put into
var totalMinutes = 3;
function startTimer() {
// running is being started and the current time is put into the variable
running = true
now = new Date()
now = now.getTime()
// Variable endTime gets the time plus the maximum time
endTime = now + (1000 * 60 * totalMinutes);
showCountDown()
}
function showCountDown() {
// same as startTimer, time is saved in variable now
var now = new Date()
now = now.getTime()
if (endTime - now <= 0) {
// Variable timerID gets clearTimeout -->http://de.selfhtml.org/javascript/objekte/window.htm#clear_timeout
clearTimeout(timerID)
// boolean running set to false
running = false
alert("Ihr Resultat wird nun ausgewertet!")
} else {
// delta is being calculated
var delta = new Date(endTime - now)
var theMin = delta.getMinutes()
var theSec = delta.getSeconds()
var theTime = theMin
// show seconds and minutes
theTime += ((theSec < 10) ? ":0" : ":") + theSec
document.getElementById('CheckResults').innerHTML = " (Übung in " + theTime + " Minuten abgelaufen)"
if (running) {
timerID = setTimeout("showCountDown()",900)
}
}
}
</script>

You might want to use window.setInterval for a start. Here is a short example. Create a blank html page, put the script into the head section, and the markup into the body section. I wasn't able to post it with proper html and body tags
<script>
function countDownTimer(msecGranularity, output) {
var secRunningTime, startTime, endTime, onFinish, interval;
function heartBeat() {
var diff = endTime - new Date();
output.innerHTML = diff / 1000;
if (diff < 0) {
window.clearInterval(interval);
onFinish();
};
};
this.start = function (secRunningTime, finishHandler) {
onFinish = finishHandler;
startTime = new Date();
endTime = startTime.setSeconds(startTime.getSeconds() + secRunningTime);
interval = window.setInterval(heartBeat, msecGranularity);
}
};
function startTimer(duration, granularity) {
var output = document.createElement("div");
document.getElementById("timerOutputs").appendChild(output);
var t = new countDownTimer(granularity, output);
t.start(duration, function () { output.innerHTML = 'TIMER FINISHED' });
};
</script>
In the HTML place these to start the timer class.
<button onclick="startTimer(60,100)">Start a new 60 seconds timer with 100 msec granularity</button><br />
<button onclick="startTimer(600,1000)">Start a new 600 seconds timer with 1000 msec granularity</button>
<div id="timerOutputs">
</div>

Related

Start javascript stopwatch from a specific dynamic value

Before asking the question I would like to inform you that I've already searched in the questions with related topics , but my issues are different from others. Actually, I am building a "Javascript stopwatch", but there are some issues in the script that I've tried and searched to solve but can't find none. There are there issues in the stopwatch:
The stopwatch restarts automatically when page reloads even though the timer was stopped by the "stop_btn".
The stopwatch restarts automatically with the time comparing starting time and present time when page reloads; the paused time is totally ignored !
Can the stopwatch be started from a specific dynamic value; something like PHP variable as:
$time = "01:06:39"; ?
The Javascript:
var timer;
var startTime;
var isRunning = false;
var waitedTime = 0;
var stoppedTime = 0;
function start() {
if (isRunning) return;
isRunning = true;
startTime = parseInt(localStorage.getItem('startTime') || Date.now());
if (timer) {
waitedTime += (Date.now() - stoppedTime);
}
localStorage.setItem('startTime', startTime);
timer = setInterval(clockTick, 100);
}
function stop() {
isRunning = false;
clearInterval(timer);
stoppedTime = Date.now();
}
function reset() {
isRunning = false;
stoppedTime = 0;
waitedTime = 0;
clearInterval(timer);
timer = undefined;
localStorage.removeItem('startTime');
document.getElementById('display-area').innerHTML = "00:00:00.000";
}
function clockTick() {
var currentTime = Date.now(),
timeElapsed = new Date(currentTime - startTime - waitedTime),
hours = timeElapsed.getUTCHours(),
mins = timeElapsed.getUTCMinutes(),
secs = timeElapsed.getUTCSeconds(),
ms = timeElapsed.getUTCMilliseconds(),
display = document.getElementById("display-area");
display.innerHTML =
(hours > 9 ? hours : "0" + hours) + ":" +
(mins > 9 ? mins : "0" + mins) + ":" +
(secs > 9 ? secs : "0" + secs) + "." +
(ms > 99 ? ms : ms > 9 ? "0" + ms : "00" + ms);
};
var stopBtn = document.getElementById('stop_btn');
var startBtn = document.getElementById('start_btn');
var resetBtn = document.getElementById('reset_btn');
stopBtn.addEventListener('click', function() {
stop();
});
startBtn.addEventListener('click', function() {
start();
});
resetBtn.addEventListener('click', function() {
reset();
})
start();
Can anyone help please ?
You can add this new variable and then use it in the start function. If the custom time is defined then localstorage or current date will be ignored.
var customStartTime = new Date() // enter your custom date in the Date() function.
Then modify the starttime in the start() function
startTime = customStartTime || parseInt(localStorage.getItem('startTime') || Date.now());
Have you considered using window.onload handler from which you can load stopwatch value after page reload, I think this should cover first 2 issues you mentioned.
Also when you reload page stoppedTime variable will be 0, use localStorage to cache stoppedTime.

Getting a JavaScript value into a variabe

My 14 yr old son is working on a Science Project looking at reaction time and age. He is setting up a little web app to test people - When a page is loaded a timer starts and there is a delay in a STOP button appearing (4 secs for this example). When they click the stop button, the timer stops.
He's done a great job of coding all of that so far. He is using a piece of JavaScript that he found and has modified it to his needs.
His issue - how to pass the stopped time into a variable and then pass that to another page. He is able to successfully do it if the variable is static ie "Hello."
What is wrong with the function stop(); in this example? He currently gets a [object HTMLSpanElement]
var clsStopwatch = function() {
// Private vars
var startAt = 0; // Time of last start / resume. (0 if not running)
var lapTime = 0; // Time on the clock when last stopped in milliseconds
var now = function() {
return (new Date()).getTime();
};
// Public methods
// Start or resume
this.start = function() {
startAt = startAt ? startAt : now();
};
// Stop or pause
this.stop = function() {
// If running, update elapsed time otherwise keep it
lapTime = startAt ? lapTime + now() - startAt : lapTime;
startAt = 0; // Paused
};
// Reset
this.reset = function() {
lapTime = startAt = 0;
};
// Duration
this.time = function() {
return lapTime + (startAt ? now() - startAt : 0);
};
};
var x = new clsStopwatch();
var $time;
var clocktimer;
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
}
function update() {
$time.innerHTML = formatTime(x.time());
}
function start() {
$time = document.getElementById('time');
update();
clocktimer = setInterval("update()", 1);
x.start();
$(document).ready(function() { $('#mybutton').delay(4000).fadeIn(0);});
}
function stop() {
x.stop();
//var varTime = "Hello";
var varTime = document.getElementById('time');
window.location.href = "somephpfile.php?etime=" + varTime;
}
The var varTime = document.getElementById('time') is assigning the element to the varible, which is fine and not a bad option however I believe your son only needs the HTML text of that element.
There are two options. The first option keeps the time element in the function for possible expansion later.
function stop() {
x.stop();
var varTime = document.getElementById('time');
if (varTime) {
window.location.href = "somephpfile.php?etime=" + varTime.innerHTML;
}
}
Or just extract the required text and send it - even if it is empty.
function stop() {
x.stop();
if (document.getElementById('time')) {
window.location.href = "somephpfile.php?etime=" + document.getElementById('time').innerHTML;
}
}
You need to read the innerHTML of the element instead if just reading element itself. This can be accomplished by :
function stop() {
x.stop();
//var varTime = "Hello";
var varTime = document.getElementById('time').innerHTML;
window.location.href = "somephpfile.php?etime=" +
}

How to get the time difference between double clicks using jquery?

I want to get the time difference in between two clicks on a single button.
I have my markup like this
click here
I am using this code to get the time difference between two clicks.
var clickedTime = '';
var lastClicked = '';
$('body').on('click', 'a', function(e) {
var d = new Date();
clickedTime = lastClicked;
lastClicked = d.getTime();
console.log(clickedTime);
console.log(lastClicked);
});
But its showing the same time in both console. So can someone tell me how to get the time difference?
Here is a simple jQuery function to return the time difference in the desired format for every x clicks - Demo
<button>Get Time Difference</button>
(function ($) {
$.fn.clickTimer = function ($param, $numbClicks) {
function msTotime(ms) {
var mill = ms % 1000;
var seconds = Math.floor((ms / 1000) % 60);
var minutes = Math.floor((ms / (60 * 1000)) % 60);
switch ($param) {
case "ms":
return ms;
break;
case "s":
return seconds;
break;
default:
return [minutes, seconds, mill];
}
}
var counter = 0;
var Start_Time;
this.click(function (event) {
counter++;
if (counter == $numbClicks) {
counter = 0;
var now = event.timeStamp;
Diff = now - Start_Time;
console.log(msTotime(Diff));
} else {
Start_Time = event.timeStamp;
}
});
return this;
};
})(jQuery);
Usage :
$(selector).clickTimer(time format , number of clicks);
$("button").clickTimer("ms", 2);
// returns time difference in milliseconds for every 2 clicks
$("button").clickTimer("s", 2);
// returns time difference in seconds
$("button").clickTimer(false, 2);
// returns an array [minutes, seconds, milliseconds]
Let me know what you think. This is definitely not a perfect solution but it may get you started.
You can use Date.prototype.getTime() to get time of click event.
var click = 0;
var time;
var difference;
$("a").click(function(){
var date = new Date();
click += 1;
if (click == 2) {
difference = date.getTime() - time;
click = 0;
console.log(difference);
}
else
time = date.getTime();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<a>Please double click on me!</a>
Or use Event.timeStamp property of event.
var click = 0;
var time;
var difference;
$("a").click(function(e){
click += 1;
if (click == 2) {
difference = e.timeStamp - time;
click = 0;
console.log(difference);
}
else
time = e.timeStamp;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<a>Please double click on me!</a>
Note that the codes return diffrence time in milisecond.

Javascript: restarting countdown timer doesn't work as I expect it to

I am making a countdown timer that should be reseting and starting anew every 10 seconds.
This is the code I came up with by now:
function count(){
var end_date = new Date().getTime()+10*1000;
setInterval(function(){
var current_date = new Date().getTime();
var seconds_left = parseInt((end_date - current_date) / 1000);
document.getElementById("countdown").innerHTML = seconds_left + " seconds ";
}, 1000);
}
setInterval(function(){count()}, 10*1000);
It is supposed to function as follows:
+ I set interval that will restart count() every 10 seconds.
+ count() defines end_date - a date 10 seconds from now.
+ then count() sets interval that will restart every 1 second.
+ every 1 second seconds_left variable is changed according to how current_date changed with respect to end_date.
+ as soon as seconds_left becomes 0, setInterval from step 1 fires and starts count() anew.
Which step am I implementing the wrong way? Do I misunderstand the functioning of setInterval()?
Here is my JsFiddle: http://jsfiddle.net/sy5stjun/ .
My guess is that each call is in its own new object and you get multiple instances of itself fighting ever 10 seconds.
Using your approach using date objects here is a possible re-write:
var tmr = null;
var time;
function bigInterval() {
clearInterval(tmr);
time = (new Date()).valueOf() + (10 * 1000);
smallInterval();
tmr = setInterval(smallInterval, 500);
}
function smallInterval() {
var cur = (new Date()).valueOf();
var seconds_left = parseInt((time - cur) / 1000);
document.getElementById("countdown").innerHTML = seconds_left + " seconds";
}
bigInterval();
setInterval(bigInterval, 10*1000);
In the above code I've updated the small timer to be 500ms instead of 1000ms as it won't exactly line up with the system clock at 1000 and you get visual jumps in the numbers.
If exact timing isn't 100% important then here is a possible shorter method:
var t = 10;
setInterval(function() {
document.getElementById("countdown").innerHTML = t + " seconds";
t--;
if (t <= 0) {
t = 10;
}
}, 1000);
There are a few things going on, here. You're not specific why you have to set another interval inside your loop, but there are a lot easier ways to accomplish what you're going for. Another approach follows:
HTML:
<!-- string concatenation is expensive in any language.
Only update what has to change to optimize -->
<h1 id='countdown'><span id="ct"></span> seconds </h1>
JS:
// For one thing, grabbing a new reference to the
// dom object each interval is wasteful, and could interfere with
// timing, so get it outside your timer, and store it in a var scoped
// appropriately.
var ct = document.getElementById("ct");
// set your start
var ctStart = 10;
// set your counter to the start
var ctDown = ctStart;
var count = function() {
// decrement your counter
ctDown = ctDown - 1;
// update the DOM
ct.innerHTML = ctDown;
// if you get to 0, reset your counter
if(ctDown == 0) { ctDown = ctStart; }
};
// save a reference to the interval, in case you need to cancel it
// Also, you only need to include a reference to the function you're
// trying to call, here. You don't need to wrap it in an anonymous function
var timer = window.setInterval(count, 1000);
My jsFiddle available for tinkering, here: http://jsfiddle.net/21d7rf6s/

Javascript reset countdown

Hello
I have a problem with countdown by javascript, i wrote a script and not bad.
i need reload countdown after few minute by ajax (json) but after loading new data script does not work properly.
after obtaining a new time counting time pours or not display!
help me pleas
thanks :)
var d = today();
function today(){
now = new Date().getTime();
return Math.round(now/1000);
}
function countdown(time1,id)
{
off = today() - d;
time = time1 - off;
h = Math.floor(time / 3600);
m = Math.floor(time / 60) % 60;
s = time % 60;
t = h + ":";
if(m < 10){ t += "0"; }
t += m + ":";
if (s < 10) { t += "0"; }
t += s;
//done
if(m <= 0 && s <= 0){
$("#"+id).html("00:00:00");
return;
}
$("#"+id).html(t).show();
var sto = window.setTimeout("countdown('"+time1+"','"+id+"')", 1000);
}
$(document).ready(function(){
//clearTimeout(sto);
countdown(1000, 'timer1');
countdown(1200, 'timer2');
//example (instead of json)
setTimeout(function(){
countdown(3000, 'timer1');
countdown(3200, 'timer2');
//alert('after click ok scripts is worked!');
}, 3000)
});
You can reset a timeout by doing window.clearTimeout(sto).
James Khoury suggests removing the var keyword from sto after declaring var sto; in the global namespace.
Below I summarize how to do these kinds of timing things in javascript:
Let's begin with some date and time manipulation functions:
// Time functions
// default unit is the millisecond
var sec = 1000;
var ms = 1;
function formatSeconds(time) {
var seconds = Math.floor(time/1000);
with (Math) {
var sec = seconds % 60;
var min = floor(seconds/60) % 60;
var hr = floor(seconds/3600);
}
return hr+':'+min+':'+sec;
}
function now() {
return (new Date()).getTime();
}
Now the actual interesting code:
// Timeout functions
function callPeriodically(params) {
/*
* PARAMS: {callback=function, callbackInterval=int, cleanupCallback=function}
*
* WHAT THIS FUNCTION DOES:
* Calls [[callback()]] every [[callbackInterval]] milliseconds;
* (The [[callback()]] function should return false if it wishes
* to abort callbacks.)
*
* RETURN VALUE: a function which, when called, will abort the periodic callbacks.
*
* Nomatter how periodic callbacks are aborted, the [[cleanupCallback()]] function
* is always run last thing.
*/
var callback = params['callback'];
var callbackInterval = params['callbackInterval'];
var cleanupCallback = params['cleanup'];
var timeout = window.setTimeout(makeClock());
var timer = function() {
if (callback()) # stop if callback() returns false
timeout = window.setTimeout(timer, callbackInterval);
else if (cleanupCallback)
cleanupCallback();
};
var cancel = function() {
window.clearTimeout(timeout);
cleanupCallback();
}
return cancel;
}
Making a clock callback which uses the above machinery:
function makeClockCallback(duration, htmlId) {
// enclose endTime in a closure:
var startTime = now();
var endTime = startTime + duration;
var countdown = function() {
var timeLeft = endTime - now();
$('#'+htmlId).html(formatSeconds(timeLeft));
return timeLeft>0; # continue as long as timeLeft>0
};
return countdown;
}
Now let's test it:
// Demo
function makeAndRunClock(htmlId) {
return callPeriodically({
callback = makeClockCallback(1000*sec, htmlId),
callbackInterval = 1000*ms,
cleanupCallback = function() {
alert(htmlId+' has been cancelled!');
}
);
}
var abortClock1 = makeAndRunClock(7*sec); // will naturally stop after 7sec
var abortClock2 = makeAndRunClock(10*sec); // will naturally stop after 10sec
window.setTimeout(
function() {
abortClock1(); // force clock1 to stop after 4sec
},
4*sec
);
There are a few syntax errors, but there you go.

Categories

Resources