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>
Related
I have a Javascript function which are doing the following functions,
Hide a div content when a button click.
Getting a input time (h:m:s) from a html input field and countdown them.
Showing the counting result in a html p tag.
function countdownTimeStart() {
/* hide the timer panel div when start button click*/
document.getElementById('timer_panel',).
innerHTML=document.getElementById('time_count').innerHTML;
/* Start count the time in timer panel */
/* Start count the time in timer panel */
var time = document.getElementById("picker-dates").value;
time = time.split(':');
var date = new Date();
var countDownDate = date.setHours(time[0], time[1], time[2]);
var x = setInterval(function() {
// set hours, minutes and seconds, decrease seconds
var hours = time[0];
var minutes = time[1];
var seconds = time[2]--;
// if seconds are negative, set them to 59 and reduce minutes
if (time[2] == -1) {
time[1]--;
time[2] = 59
}
// if minutes are negative, set them to 59 and reduce hours
if (time[1] == -1) {
time[0]--;
time[1] = 59
}
// Output the result in an element with id="demo"
// add leading zero for seconds if seconds lower than 10
if (seconds < 10) {
document.getElementById("demo").innerHTML = hours + ": " + minutes + ": " + "0" + seconds + " ";
} else {
document.getElementById("demo").innerHTML = hours + ": " + minutes + ": " + seconds + " ";
}
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "00:00:00";
}
}, 1000);
}
<div id="timer_panel" class="timer_panel1>
<input type = " text " id = "picker-dates ">
<button id="start " onclick="countdownTimeStart(); ">
</div>
<div id="time_count " class="time_count " style="visibility:hidden;>
<p id="demo" class="count"></p>
</div>
Problem is the time counting result not showing inside of the "demo" p tag when hiding timer panel div. How can I solve this, can anyone help me !
I've noticed a few mistakes in your code, I'll try to outline them as clearly as I can for you.
HTML
Firstly in your HTML you haven't closed your input tags. Also there was a typo on your div with the id time_count that didn't have closed quotations.
As some other people have mentioned, you also had a typo in your id name.
But the biggest thing, is that your p tag is wrapped in the div that inline you have set to visibility:hidden. Your JS doesn't address this. Once I moved the p tag out from this div, I was able to see an output.
However...
JavaScript
The Javascript code has some minor adjustments too. Why do you create a date object that you don't use? I'd delete this is you don't need it.
I would also suggest you store your element for use later, rather than calling document.getElementById('demo') everytime you use it, like so:
var el = document.getElementById('demo');
How to stop once the timer reaches 0
I've added this logic to your if else block
if( seconds == 0 && minutes == 0 && hours == 0 ){
clearInterval(x);
el.innerHTML = "00:00:00";
}
It uses code that you were trying to implement earlier but wasn't quite right. Moving it to here should do the trick. Check out the codepen where I have updated the code also.
Cancel the timer
Firstly you'll need to add a new button to your HTML
<button id="cancel">Cancel</button>
Then within your setInterval function I've added the following code:
// select cancel button
var cancel = document.getElementById('cancel');
// set up cancel functionality
// create a function to handle the cancel
function cancelCountdown(){
el.innerHTML = "00:00:00";
clearInterval(x);
}
// attach listener to cancel
// if cancel button is clicked
cancel.addEventListener( 'click', cancelCountdown);
Pause the timer
Okay, so we need to add another button to your HTML with a id of pause like so:
<button id="pause" >pause</button>
Then we add this pause functionality just below the code we put
in to clear the timer.
// select the pause button
var pause = document.getElementById('pause');
// create pause function
function pauseCountdown(){
// grab the current time
let pauseTime = hours+":"+minutes+":"+seconds;
// set that time into the timeInput
// so that next time 'Start' is pressed
// the paused time will be used
let timeInput = document.getElementById('picker-dates');
timeInput.value = pauseTime;
// stop the time to 'pause'
clearInterval(x);
}
// add listener to catch the pause
pause.addEventListener('click' , pauseCountdown);
How does it work? Well we're kinda cheating. You can't pause an Interval timer (that I've been able to find anyway) but you can take
the values you're using for the time and store them. Then when the start button is pressed, the timer will start again with the paused interval time as the countdown time. I hope that makes sense. Check out the codepen to see the example working.
Hope this helps!
Cheers,
Your p element has id demo1, but your code uses demo.
I need to create a very simple Javascript-based counter, which counts currency (so two decimal places) and increases in value by 0.18 every minute. The idea is to represent "live" estimated savings by the company's new solar panels, and this counter will be started and stopped by an employee every day, to continue the next day.
I found a fiddle by somebody else for a start/resume counter: http://jsfiddle.net/f9X6J/
HTML:
<span id="hour"></span>
<span id="min"></span>
<span id="sec"></span>
<input id="pauseButton" type="button" value="Pause">
<input id="resumeButton" type="button" value="Resume">
Javascript:
var Clock = {
totalSeconds: 1000,
start: function () {
var self = this;
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(Math.floor(self.totalSeconds / 3600));
$("#min").text(Math.floor(self.totalSeconds / 60 % 60));
$("#sec").text(parseInt(self.totalSeconds % 60));
}, 1000);
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
if (!this.interval) this.start();
}
};
Clock.start();
$('#pauseButton').click(function () { Clock.pause(); });
$('#resumeButton').click(function () { Clock.resume(); });
This is great so far, but I please need the following:
It must not calculate time, but rather money.
It must be saved to the server in case the computer shuts off.
Thanks!
For the sake of beginners in 2019. The answer to the two questions are,
1) Keep a counter outside the clock object and keep adding 1 to it every second the clock is active. This will give the total number of seconds the clock has been active. This can be then converted to total savings at any point.
2) Don't jump on to server side stuff just yet. Try to store the total with localStorage which persists even if the computer is switched off until browsing data is cleared in the browser. This will avoid lot of added complexity. An example for storing values locally and reading from them is below.
<html>
<head></head>
<body>
<div id="counter"></div>
</body>
<script>
var counter;
if( localStorage.getItem("counter") == null) {
counter = 0;
localStorage.setItem("counter", counter);
} else {
counter = localStorage.getItem("counter");
}
document.getElementById('counter').textContent = counter;
setInterval(function(){
counter = parseInt(counter)+1;
localStorage.setItem("counter", counter);
document.getElementById('counter').textContent = counter;
},1000);
</script>
</html>
Hope this provides a right direction.
I am currently trying to make a visual countdown for my user for when the animation is finished. My current attempt looks somewhat like this:
function setClassAndFire(){
timer = setInterval(function () {
t--;
$(this).attr('class', 'timerAnimation');
countdownTimer();
if (t === 0) {
clearInterval(timer);
timer = undefined;
funcForCall();
}
}, 1000);
}
function countdownTimer(){
var timerCurrentWidth = $('.timerAnimation').width(),
timerMaxWidth = $("#awardQueueText").width(),
pxPerSecond = timerMaxWidth / 60,
currentCountdown = timerCurrentWidth / pxPerSecond;
currentCountdown = Math.round(currentCountdown);
document.getElementById("timer").innerHTML = "<span style='white-space : nowrap;'>Animation ends in:</br></span>"+
"<span style='white-space : nowrap;'>" + currentCountdown + " sec.</span>";
}
Important to know is that the animation only displays the time until we may be able to send an API call. So the animation will be re-engaged if we have something in queue.
So as you can see my current attempt works, but is some-what cluncky:
The countdown sometimes fails to subtract a second and "fixes"
that with a 2 seconds subtract in the next attempt.
This is probably caused by the Math.round() for currentCountdown, but is there a work around for that? I mean I have the max possible width of the animation object and can seperate it from the current width.
Is there a way to bring it to work? We need to relate the timer to the animation to achive desired behavior. So when the animation count hits 25, I want that the displayed number is 25 as well!
You got this problem because you got the number from the width andh the width can't have decimals (or better, they can be but they are gonna be truncated sometimes).
So my suggestion is to use a differente variable for the number you will show and the width of the DOM element.
It seems to me that the variable t is what I am talking about, so just try to use it.
function setClassAndFire(){
timer = setInterval(function () {
t--; //What is t?
$(this).attr('class', 'timerAnimation');
countdownTimer(t);
if (t === 0) {
clearInterval(timer);
timer = undefined;
funcForCall();
}
}, 1000);
}
function countdownTimer(t){
document.getElementById("timer").innerHTML = "<span style='white-space : nowrap;'>Animation ends in:</br></span>"+
"<span style='white-space : nowrap;'>" + t+ " sec.</span>";
}
I have a gaming website and I want to put a advertisement before the game. So can someone tell me how to show the advertisement div for 15 seconds which says below it. "The game will start in [time left] seconds". Then one the time is up then it will show the div which holds the game. In javascript please.
Thank you
I would recommend taking a looking at setTimeout. It allows you do something after a certain time. If you need more help let us know.
EDIT: I'm sorry I misread your question. A more appropriate method you should use is setInterval so every second during the 15 seconds, you can show the time. Speransky's answer has the right idea.
Demo: http://jsfiddle.net/myDTK/1
var secondsLeft = 15;
var delay = 1000; // 1 second
var interval = setInterval(function () {
if (secondsLeft > 0) {
document.getElementById('timer').innerHTML = 'The game will start in ' + secondsLeft + ' seconds...';
secondsLeft -= 1;
} else {
document.getElementById('timer').style.display = 'none';
clearInterval(interval);
document.getElementById('game').style.display = 'block';
}
}, delay);
function doSome() {
//do some
}
setTimeout(function(){
doSome();
}, 15000);
Have a look at the setTimeout function
eg.
setTimeout(function(){
//code to hide the div and how game div
}, 15000);
Here's a live example using jQuery.
Basically just make a function that adds the div, call that function whenever you need to, and then in that function do setTimeout(removeFunction, 15000) to call the remove function 15 secs later.
In order to do the countdown timer, you can call a function updateTimer once per second (again, setTimeout(updateTimer, 1000)) and have that function simply search for the timer and decrement the counter.
As I don't have much knowledge of javascript and I need your help. My problem is like this:
I am using setInterval() for increasing the value of i every after 1 minutes and I am using this code:
var i = minutes;
function decrementMin() {
if(i>=0)
{
i--;
}
if(i==0)
{
alert('Minute = Congratulation your time begin now!');
}
document.getElementById('minutes').innerHTML = i + "minutes";
}
setInterval('decrementMin()',60000);
The problem is I want to show first message in <div id='minutes'></div> when page loads, but it shows the message after 1 minutes interval. If there is something that I am missing in my code please let me know.
Your problem is that you are setting the interval before the first message is displayed. Instead, you can call the function straight away and then set the interval. Also, you need to clear the interval once you've reached 0:
var i = minutes;
var intID;
function decrementMin() {
if(i>=0)
{
i--;
}
if(i==0)
{
clearInterval(intID);
alert('Minute = Congratulations my friend your time begins now!');
}
document.getElementById('minutes').innerHTML = i + "minutes";
}
decrementMin();
intID = setInterval(decrementMin, 60000);
This way you call your function straight away, and then set it to run every minute. Once you reach 0, you clear the interval so that the function doesn't count to "-1", etc.