Simple countdown using minutes and seconds - javascript

I need a countdown that will refresh a page, and I think I've finally got it, except for one thing. I'd like the countdown to be in minutes and seconds, not just seconds (the countdown is for one hour). A simple MM:SS format would be fine, but also writing out minutes and seconds would work. Can anybody help?
<SCRIPT LANGUAGE="JavaScript">
<!--
var counterobj = document.all ? counter : document.getElementById("counter");
var countdownfrom = 3600; //countdown period in seconds
var currentsecond = counterobj.innerHTML = countdownfrom+1;
function countdown()
{
if (currentsecond!=1)
{
currentsecond-=1;
counterobj.innerHTML = currentsecond;
}
else
{
self.location.reload();
return;
}
setTimeout("countdown()",1000)
}
countdown()
//-->
</script>

Calculate minutes using a floor doing like
minute = Math.floor(currentsecond/60);
Then just output as normal.
edit -- fixed! Hopefully! (accidentally said to use mod -- you need to use Floor, I believe)

Related

How can I refresh a page every 5 minutes starting at 8:01 a.m. and then 8:06 a.m. and so on.

<html>
<head>Harshal</head>
<script>
var limit="5:0"
var doctitle = document.title
var parselimit=limit.split(":")
parselimit=parselimit[0]*60+parselimit[1]*1
function beginrefresh(){
if (parselimit==1)
window.location.reload()
else{
parselimit-=1
curmin=Math.floor(parselimit/60)
cursec=parselimit%60
if (curmin!=0)
curtime=curmin+" minutes and "+cursec+" seconds left until page refresh!"
else
curtime=cursec+" seconds left until page refresh!"
document.title = doctitle + ' (' + curtime +')'
setTimeout("beginrefresh()",1000)
}
}
if (window.addEventListener)
window.addEventListener("load", beginrefresh, false)
else if (window.attachEvent)
window.attachEvent("load", beginrefresh)
</script>
</html>
This is my demo code. I'm refreshing the page every 5 minutes when someone clicks on the link and the tab title counts down the 5 fives. However, I cannot figure out how I can start the refresh at 8:01 a.m and then again at 8:06 am and then again at 8:11 a.m. and just keeps going and doesn't depend on when someone clicks on it.
Any help?
To achieve expected result, use SetInterval
SetInterval for every minute (1000*60)
GetTime in Hours and Minutes separately
Start after 8am or anytime after 8am
Check every 5 mins to refresh
refresh window
setInterval(function(){
var currTimeHr = new Date().getHours();
var currTimeMin = new Date().getMinutes();
if(currTimeHr >= 8){ //start at 8 or at any point after 8am
if(currTimeMin%5 === 0){ // check every 5 mins
window.location.reload(true); //refresh page
}
}
}, 1000*60)
code sample - https://codepen.io/nagasai/pen/MXVWxb?editors=1010
use set interval.
setInterval(function() {
window.location.reload();
}, 300000);
setinterval is in ms (5mins = 300k ms)
The new page (after refresh) has no awareness of the previous page's state. So you need a way to pass that state forward, through a query parameter or something.
My approach would be to just reload the page when they clicked the link, and have the new page set itself to refresh after 5 minutes (keeping the same url so we're loading the page with the refresh code).
if(window.location.search.includes('refresh')){
setTimeout(function(){//we're in "refresh mode" so just wait 5 minutes and do it again
location.href = location.href;
}, 1000 * 60 * 5);
}
refresh every five minutes
the example doesn't seem to work because the navigation. but it should work in theory
To start at specified time use the following "wait" function
var startHour = 8;
var startMinute = 5;
function wait() {
var startTime = currentTime = new Date();
startTime.setHours(startHour);
startTime.setMinutes(startMinute);
if (startTime < currentTime) {
setTimeout(wait, 1000);
} else {
// run refresh function here
}
}

How to stop resetting a JavaScript timer while refreshing the page

I am doing an online examination page. In this page I have a countdown timer that counts down by a value from the database. It's working fine but when I refresh the page it resets. I have to stop the timer from resetting.
Here is my JavaScript timer code:
<script type="text/javascript">
function CountDown(duration, display) {
if (!isNaN(duration)) {
var timer = duration, minutes, seconds;
var interVal = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
$(display).html("<b>" +"Time Remaining: "+ minutes + "m : " + seconds + "s" + "</b>");
if (--timer < 0) {
timer = duration;
SubmitFunction();
$('#display').empty();
clearInterval(interVal)
}
},1000);
}
}
function SubmitFunction(){
$('#result').click();
}
CountDown(<?php echo $t*30; ?>,$('#display')); //$t comes from database
function disable_f5(e) {
if ((e.which || e.keyCode) == 116) {
e.preventDefault();
}
}
$(document).ready(function(){
$(document).bind("keydown", disable_f5);
});
</script>
I just saw your question and am going to take a crack at it. One thing that I recommend is trying to commit the values to local storage. You could add an event listener, have it specify to listen for a reload, and on that reload commit the integer value to local storage in JSON format. Just an idea.
If you are using a db already, what about adding a table or an extra field to an existing table that registers the datetime that the user commenced the examination and then on each page load - you can get the commencement time from the db, do some funky calculations and then display the remaining time.
That way you are not relying on the calculation in browser keeping track (although I would probably try session storage for it as already suggested), but a constant start time that you can confidently calculate from.
try this as an approach - note only skeleton of code listed to demonstrate approach. I would personally set the datetime in the db though.
//at commencement of exam
//js var commencementTime = (//calculation to get current time);
localStorage.setItem('commencementTime ',commencementTime );
//on page reload
var commencementTime= localStorage.getItem('commencementTime ');
if(commencementTime){
//code for calculating countdown}

How can I build a secure timer based button?

here's what I mean:
I have written up a simple timer that counts down from 5 minutes. At the end of 5 minutes, I'd like to display a button for my user to press. You can see my code at the end of this post.
I do not want the user to be able to press see the button before the timer runs out. I don't want the user to be able to go into the JS console and call "document.getElementById("button").style.display = 'block';" and have access to the button.
What are some ways I can do this, preferably entirely on the client side? Is there a way to do this entirely on the client side?
My backend is Ruby on Rails - if there's an easy solution using RoR, I'd be curious about that too. But frankly, I'd love to know if there's a fully client side way of doing this!
<html>
<script>
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer(timerIntervalId) {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (minutes == "00" && seconds == "00" && timerIntervalId != undefined) {
clearInterval(timerIntervalId);
document.getElementById("button").style.display = 'block';
}
if (diff <= 0) {
start = Date.now() + 1000;
}
};
timer();
var timerIntervalId = setInterval(function() { timer(timerIntervalId) }, 1000);
}
window.onload = function () {
var timerLength = 60 * .15,
display = document.querySelector('#time');
startTimer(timerLength, display);
};
</script>
<body>
<div>Registration closes in <span id="time"></span> minutes!</div>
<div id = "button" style = "display: none;">BUTTON</div>
</body>
</html>
I hate to say it bud, but there is no such thing as secure in javascript. A user with a little knowledge will be able to do anything they want to your code. But to attempt to give a suggestions
if (minutes == "00" && seconds == "00" && timerIntervalId != undefined) {
clearInterval(timerIntervalId);
///document.getElementById("button").style.display = 'block';
$("<div>").attr('id', 'button').appendTo($("#placeholder")).text("button")
}
<body>
<div>Registration closes in <span id="time"></span> minutes!</div>
<div id="placeholder">
</div>
</body>
</html>
this way the button doesnt exist until you create it at the end of the timer
https://jsfiddle.net/u3bae0uj/
There is no fully client side solution. Because if yo implement this fully using client side, user can at some way change the timer (as you said, show button).
To be sure that 5 minutes will pass you will have to communicate with server, but can implement this using ajax.
At timer start you can call some action at server and start timer on server side, using sessions variable, when 5 minutes pass you execute ajax call on other action an check if 5 minutes have pass (this way you get 5 minutes, and user can not change it on client).
If 5 minutes have passed, you return html to user, inside html you return the button you want to show, so user can not inspect html, and set it visible, because server returns button after 5 minutes, and then user can click on it.

Showing timer countdown

In my game I have set the timer to 30000ms (30 secs). When the timer ends the game ends. I want to show the user the timer to give them some idea of how long they have left. How would I do this, I have tried to do it like this:
setTimeout(function() {
$("#message").html('Thank you for playing. </br> You answered </br>' + hit + '/' + attempted + ' correctly. </br> Press "Play" to start again.').fadeIn('slow');
$(".character").fadeIn('slow');
}, 500);
});
}, 30000).show('#timer'); //here I am trying to display the time in the "#timer"
}
I think I am approaching this all wrong can someone give me a point in the right direction?
Fiddle: http://jsfiddle.net/cFKHq/8/
Have a gander at this jsFiddle. You just need to change your timeout to an interval and keep a count of the seconds.
Instead of running the timer by all 30000 at once, run the timer in 1000ms increments. Each time it hits, subtract one from the counter, refresh the page, and if the counter is 0, end the game.
I changed the jsfiddle you posted to show a counter after pushing play button. See http://jsfiddle.net/cFKHq/10/
Inside your function startplay() I added a variable ttime with an initial value of 30 and I added the line $("#timer").text(--ttime); to the setInterval argument function that is called every second.
Look into using delta times. I have found this to be a great way to handle things that need to measure changes in time.
prevTime = curTime;
curTime += new Date();
deltaTime = curTime - prevTime;
This will also allow you to have a "x seconds remaining" counter if you fire off an event every 1 second, or even every 100ms. All depends on how fast you want it to go.
You need to seperate your timer logic from your "game over" logic, as the timer should tick regardless:
var secondsLeft = 30;
var timerElement = $('#timer');
(function timer() {
timerElement.text(secondsLeft);
secondsLeft--;
if (secondsLeft !== 0) {
setTimeout(function () {
timer();
}, 1000);
}
}());
http://jsfiddle.net/cFKHq/14/
Note that in this solution the 30 * 1 second timer countdown and 30 seconds of gameplay are not related or reliant on one another, which may cause some synchronicity issues if the user is on a slow machine.
You can use a global window.duration variable were you set the seconds the game will last, then decrement from that in the "one second" interval:
See working demo
At start of script:
var hit = 0;
var attempted = 0;
var target = $("#target");
window.cont = true;
window.duration = 30; //set your desired game duration in seconds
then on the "one second interval" we decrement the timer and print the timer text:
play = setInterval(function() {
if (window.cont) {
window.cont = false;
scramble();
}
window.duration--;
$('#timer').html(window.duration + ' seconds to go');
}, 1000);
Also display a "finished" text when the game ends, the relevant part follows:
setTimeout(function() {
$("#message").html('Thank you for playing. </br> You answered </br>' + hit + '/' + attempted + ' correctly. </br> Press "Play" to start again.').fadeIn('slow');
$(".character").fadeIn('slow');
$('#timer').html('Finished');
}, 500);
Here is an example: http://jsfiddle.net/RPSMJ/4/
JavaScript
var counter = 30,
timerOutput = document.getElementById('timerOutput');
(function timer() {
timerOutput.innerHTML = counter;
counter -= 1;
if (counter >= 0) {
setTimeout(function () {
timer();
}, 1000);
}
}());​
HTML
<div id='timerOutput'></div>​

Strange problem with JavaScript code

Hi Masters Of Web Development,
first I want to say that I did not believe in my eyes - I've got a piece of javascript that works just fine in IE7, and don't in Firefox!!! :)))) That was little joke. :)
So I already told you the problem (it wasn't joke), now I'm pasting the javascript:
<script type="text/javascript">
<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Begin
var ms;
ms = %%CONTENT_REFRESH%% - 5;
var stop;
stop = 0;
var myvalue;
function display() {
if (!stop) {
setTimeout("display();", 1000);
}
thetime.value = myvalue;
}
function recalc() {
var hours;
var minutes;
var seconds;
ms = ms - 1;
hours = Math.floor(ms / 3600);
minutes = Math.floor(ms / 60);
if (minutes < 10) {
minutes = "0"+minutes;
}
seconds = ms - (minutes*60) - (hours*3600);
if (seconds < 10) {
seconds = "0"+seconds;
}
myvalue = hours+":"+minutes+":"+seconds;
thetime.value = myvalue;
if (myvalue == "0:00:00") {
stop = 1;
}
if (!stop) {
setTimeout("recalc();", 1000);
}
}
// End -->
</SCRIPT>
This is very old script I know that. It takes my current remaining song time, from my winamp and countdowns in site. But as I said, it does not work in Firefox.
Body and code that calls countdown timer looks like this:
<body class="playlist_body" onLoad="recalc();display();">
Time Left In Song: <INPUT align="center" TYPE="text" Name="thetime" size=5 />
</body>
//Edit: I look at FireBug, and I saw the following error:
thetime is not defined
recalc()playlist.cgi (line 87)
function onload(event) { recalc(); display(); }(load )1 (line 2)
error source line: [Break on this error] thetime.value = myvalue;\n
The problem is that it's accessing DOM elements by name.
Add the following code to the top to declare a variable for the thetime element, add id="thetime" to the INPUT, and add a call to init(); in onload in the body element.
var thetime;
function init() {
thetime = document.getElementById('thetime');
}
By the way, you can replace the textbox with a regular DIV element by setting the div's ID to thetime, and replacing thetime.value with thetime.innerHTML.
Also, it's better to call setTimeout with a function instead of a string; you should replace "display();" and "recalc();" with display and recalc respectively.
IE has a "feature" where an element with a name attribute is placed in the window object, eg.
<div name=foo></div>
Will give you a variable "foo" -- this is non-standard, you should do
document.getElementByName("foo")
To get the timer output element.
var thetime = document.getElementById("thetime");
and add id="thetime" instead of just name="thetime" to the input

Categories