How to make a very simple countdown timer in Javascript? - javascript

I'm making a simple game which generates random numbers and user has to enter a value, if users value matches the random value generated, the user wins basically this is a beginner project. I want to make a small counter so that user has a limited time to put in the value and I want that limited time to show on the screen in a label. Lets say that you have to put the value under 30 secs and the timer will count from 1 to 30 every second. The counting from 1 to 30 will update in the label every second. This is the logic I'm trying to work on right now and I can't figure out any other way... If I've done some mistake in code please comment or if you have much more simpler way please post it down below. (pls dont vote down im at threat of account suspension)
Heres the part of my timer code:
if(timer <= 30)
{
for(var i = 0;i >= 30;i++)
{
setInterval(null,1000);
timer++;
document.getElementById("counter").innerHTML = timer+" seconds wasted";
}
alert("Time is over, you lost by "+s);
}

You could create a recursive function.
Say var countDown function(){ time = time--;
setTimeout(countDown, 1000);}
Then you need a variable time that is accessible for the countDown function.
var time = 30;
In the countDown function you could create an updateTimeElement.
Try it out.

The setInterval function has 2 parameters, a callback (an anomynous function in javascript thats triggered) and the milliseconds between each trigger of the interval.
What you are doing in your script is making an interval with nothing to do each second (this runs indefinately), then increment the timer integer and updating the DOM. However, this all executes within seconds.
I'd suggest (before you use a function) you look at the documentation to see how you can improve your script to work as you intent to ;-) Here are a few links that might help you get started:
http://www.w3schools.com/js/js_timing.asp
https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/
I wont be doing the work for you, since this is a good exercise for a beginner programmer ;-)
If you can't figure it out, leave a comment below this answer and I'll get back to you to help you if you need further assistance.

Related

Clearing Timeout After Button Clicked

I'm currently trying to code something similar to tamagotchi "care mistakes".
In this case, I'm trying to create a function which checks if the object's hunger stat is above or at 10. Once this occurs, a timer will start, and if it remains above 10 after 10 seconds, it'll be logged as a "mistake".
However, if the user does another action which reduces the hunger below 10, it'll clear the timer.
I'm unable to get the timer to clear properly at the moment despite trying the code below.
var changeHungerMood = setInterval(mistakeCheck, 5000);
function mistakeCheck() {
var mistakeTimer
function addMistake() {
stats.mistakes += 1;
}
if (stats.hunger >= 10) {
var mistakeTimer = setTimeout(addMistake, 10000);
} else {
clearTimeout(mistakeTimer);
console.log("Mistake Cleared!");
}
}
minmaxHunger("hunger", 10, 0);
At the moment, even if hunger goes below 10 after the check, the timer isn't cleared and it's still logged as a mistake. Could anyone please help? Thank you.
You should clarify what you need to accomplish in each case.
Very imperatively, you need:
To set your timer if stats.hunger >= 10, you're doing it well (except that you declare mistakeTimer with var two times... skip the second var).
When the 10 seconds are over, instead of calling addMistake, you need to check if stats.hungeris still 10 or more, and if it's the case, call your addMistake function.
So you need to add a function addMistakeIfNeeded that do the check and call addMistake if needed. And your timer should call this addMistakeIfNeeded function instead of addMistake.
And #Jonas is right, you need to put addMistake and addMistakeIfNeeded out of the mistakeCheck function.

setInterval function using jquery is causing a "blink"

Personal project using jQuery.
I'm trying to create a function that runs on the hour for 5 seconds. I've done this by getting the current minutes and acting when they are at '00'. (Although for testing the minutes need to be manually changed to the next minute, unless you want to wait an hour to see it run again.)
The function acts on 2 objects, one to add/remove a class, the other to slideUp/Down.
It works, but after the initial running, the slideDown/Up jQuery causes a "blink" every 5 seconds for the rest of the current minute.
I've tried setting the setInterval for 5000, however that hasn't solved the issue. I'm at my wits end really.
While I am also using moment.js elsewhere. This function isn't using moment(). Primarily because I haven't been able to get functions working with moment() either.
Just head to the ....
jsFiddle example
Remember to set the =='00' to the next minute -- sure makes testing easier I really appreciate anyone waiting for this to run. I know it can be a pain to have to wait a minute to see the function at work.
If you watch the function run for 5 seconds, it will stop... but continue watching.. the slideDown() will repeat every 5 seconds until the minute is no longer XX.
How can I stop this repeat??
Thanks!
There're two place for fix.
1. miss usage for 'clearInterval'
clearInterval parameter is The ID of the timer returned by the setInterval() method.
reference this link, w3c definition for clearInterval.
var intervalId = setInterval(function() { alarm(); }, 5000);
...
clearInterval(intervalId );
2. secs >= "05" condition is wrong
change string "05" to int 5.
Believe it or not I sorted it a few moments after posting this.
My conditional was off, and I thought I tried everything. Guess not.
This works
if((mins == "29") && (secs <= '05')) {
$('#focus').slideDown(500);
$('.projcnt').addClass('jump');
} else {
$('#focus').slideUp(300);
$('.projcnt').removeClass('jump');
}
And the ...
working, updated fiddle

Settimeout not working when window loses focus

I have a simple JavaScript chronograph that displays on a form field called "d2", it is used to check how long someone takes on doing a specific task:
var milisec=0
var seconds=0
var complemento1=""
document.form1.d2.value='00:00:00'
function display(){
if (milisec>=9){
milisec=0
seconds+=1
}
else{
milisec+=1
}
complemento1=complemento2=complemento3="";
if ((seconds%60)<10) complemento1="0";
if ((Math.floor(seconds/60)%60)<10) complemento2="0";
if ((Math.floor(seconds/3600))<10) complemento3="0";
document.form1.d2.value=complemento3+Math.floor(seconds/3600)+":"+complemento2+(Math.floor(seconds/60)%60)+":"+complemento1+(seconds%60)
setTimeout("display()",100)
}
The problem is that when the person opens a new tab / uses another program the timer stops, and then resumes when the window is focused again (Using Chrome). It has the weirdest behavior, because sometimes it works, sometimes it doesn't.
I saw many posts that needed a script to stop when not on focus, I want the exact opposite and searched for over an hour with no luck. Your help is greatly appreciated!
JavaScript timeouts are not guaranteed be executed at a specific time. For example if the thread is busy with something else at the time when the timer finishes, it will first finish what it is doing and then execute your timer.
Also your function does not take into account the time spend inside the display function, so a little delay will be added for each millisecond.
The correct way to implement a timer is using the system time.
So something like:
//Call at the beggining to save the start time
var start_time = new Date()
// Compute seconds (does not matter when/how often you call it.)
var milliseconds_since_start = new Date().valueOf() - start_time
The Date object can also format this period as a clock for you:
var m = new Date(milliseconds_since_start)
m.getMinutes()+":"+m.getSeconds()

Looking for a simpler JavaScript timer

Right now i have a text-based game that deals with turns, but i want to upgrade it to a timer system so that when the timer hits 0 then you gain 1 or 2 of whatever action you were doing. Also if you know how to make it randomly pick whether u get 1 item or 2 items could you please elaborate on how to do that? Thank you to all responses.
You can use setTimeout() for delaying actions for a set period of time, or setInterval() if you wish to run it periodically on a given interval.
For getting a random number either 1 or 2 you can use random():
var randomOneOrTwo = Math.floor(Math.random() * 2) + 1;
Hope you will get from here.
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
Happy Coding.....

ajax/JS timed countdown?

Let me explain what I'm trying to do.
I want to make a simple box which counts down numbers at intervals I specify.
For example, I'd like to set it to start at 150, and then I want to set it to drop by 15 every 30 seconds.
Is this possible with AJAX/Javascript? If so, could someone point me in the right direction?
Would really appreciate any help on this script, been Googling for hours now! :(
Cheers
Kieran
Have a look at the setTimeout or setInterval methods, they allow you to execute a function after a specified number of milliseconds (1000ms = 1second). Use that, to call a function that keeps dropping the number and writes it to a HTML element to the user can see it.
this isn't tested, but i hope it shows you the way to go.
var start = 150;
var drop = 15;
var interval = 30;
function countdown(){
document.getElementById('mybox').innerHTML = start;
start-=drop;
window.setTimeout("countdown",interval*1000);
}
countdown();
You may use jQuery to do that, see http://keith-wood.name/countdown.html -> tab Callbacks
Keep in mind that 30 seconds in my browser are not necessarily equal to 30 seconds in your browser. It depends on the workload of the browser.
The time difference is minor for a short time but can increase over a long time. The times will drift apart. If the times must not be equal (or nearly equal) between two visitors than such simple solution should be fine.
We had once a problem to introduce a live clock / countdown in one of our projects. We build a script with javascript, ajax and PHP for clock synchronisation (server time was timeserver).
You should use setInterval / clearInterval which is made for this kind of tasks:
function cooldown(element, start, stop, step, delay) {
var current = start;
element.innerHTML = current;
var timer = setInterval(function () {
current -= step;
if(current < stop) current=stop;
element.innerHTML = current;
if(current == stop) clearInterval(timer);
}, delay*1000);
}
Demonstrated here : http://jsfiddle.net/PCMHn/

Categories