JavaScript Countdown Timer not starting [Code Included] - javascript

I'm trying to make a countdown timer using JS, obviously.
I think my code is correct, but it does not work.
Objective of the code:
The code suppose to show a timer decreasing until it show the content which is DONE in the alst line of the code.
Problem: I've tried making an HTML page on my local machine and tested it but it didn't work, also I've uploaded it on my website and it does not work too.
Code:
<body>
<div
id="JSPractice5"
style="border-style:dotted;
padding:10px;
font-size:24px;
width:200px;
text-align:center;">
Countdown Starting
</div>
<script type="text/javascript">
var containerID = "JSPractice5";
var number = 100;
var timerID = setInterval("CountdownTimer()",1000);
function CountdownTimer() {
if(number > 1) {
number--;
ReplaceContentInContainer(containerID,number); //Mark1
}
else {
clearInterval(timerID);
ReplaceContentInContainer(containerID,'DONE!!');
}
}
</script>
</body>
If the solution of the problem is easy/stupid and you thought of down voting it, please don't do, because I'm very new to SOF and JS :)
Thanks in Advance guys.

You're missing
function ReplaceContentInContainer(id, content)
{
document.getElementById(id).innerHTML = content;
}

Redo your setInterval call to specify the function itself, rather than a string containing a call.
See http://jsfiddle.net/2zwbV/2/ for a working example.

<body>
<div
id="JSPractice5"
style="border-style:dotted;
padding:10px;
font-size:24px;
width:200px;
text-align:center;">
Countdown Starting
</div>
<script type="text/javascript">
var containerID = "JSPractice5";
var number = 100;
function CountdownTimer() {
if(number > 1) {
number--;
ReplaceContentInContainer(containerID,number);
}
else {
clearInterval(timerID);
ReplaceContentInContainer(containerID,'DONE!!');
}
}
var timerID = setInterval(CountdownTimer(),1000);
</script>
</body>
First, the timerID should be after CountdownTimer function because if not you are going to call a non existing function, second is that the function CountdownTimer should't be in quotes.

Related

How to add a number every one second so I can show or use them later?

I was wondering if anyone can help me. As I wrote in the titel I need to have an opportunity to add a number every one second to my var "number". And I'd like to use them in the future, for example: in an egg timer (as a number you substract from). What do I do wrongly? Thanks for help :)
Here's my code:
<!DOCTYPE html>
<html style="height: 100%;">
<head></head>
<body>
<p id="time"></p>
<button onclick="show()">show me</button>
<script type="text/javascript">
var number = 0
clock();
function clock(){
clock2 = setInterval(function() {
number + 1;
}, 1000);
}
function show(){
document.getElementById("time").innerHTML = number;
}
</script>
</body>
</html>
number + 1;
must be
number += 1;
Your expression is going into the nowhere of the JS parser...
Also this:
clock();//bad style
function clock(){
clock2 = setInterval(function() {
number += 1;
}, 1000);
}
can be brewed down to this:
(function (){
setInterval(function(){
number+=1;
},1000);
})()
And if you want to stop/restart it, you may make it more elegant trough this:
var stop=false,
timer=null;
function start(){
timer=timer||setInterval(function(){
if(stop){
destroyInterval(timer);
timer=null;
stop=false;
return;
}
number+=1;
},1000);
}
Use like this:
start();
start();//will do nothing
stop=true;//stops timer
if(!timer){
start();
}

JavaScript: simple counter with pause between the values doesn't work

I'm starter in JavaScript and I try to make simple code to print numbers (0-100) , but with pause in printing, for every next number(for exp. 3 seconds pause).
Code doesn't work properly... It waits 3 seconds and print the last number (100 in my case). Can you help me, where is my mistake?
This is the code:
<html>
<head>
<script type="text/javascript">
function funkcija_polnac()
{
var i = 0;
while (i <= 100) {
setTimeout(function(){ document.write(i + '%');}, 3000);
i++;
}
}</script>
</head>
<body>
<div style="margin: 0px auto;" onclick="funkcija_polnac()">Start</div>
</body>
</html>
What your code does is schedule 101 function callbacks, all of which will happen one right after another about three seconds after the code runs, and all of which will use the i variable, not its value as of when the function was created. So after three seconds you get 101 iterations of the value 101. This is because the functions you're creating are "closures over" the i variable (more accurately, the context in which the variable was created), and so they have an enduring reference to the variable and see its value as of when they use it, not as of when they were created. More about closures on my blog: Closures are not complicated
Or at least, that's what you'd see if it weren't that document.write, when used after initial parsing, blows away the page entirely. Basically: Don't use document.write. :-)
To fix it, you would schedule a single call to a function that, once it's run, schedules the next call. And you'd use the DOM or similar rather than document.write to see the output.
Example:
// NOTE: I used 30ms rather than 3000ms so it runs faster
var i = 0;
showOne();
function showOne() {
display(i);
++i;
if (i <= 100) {
setTimeout(showOne, 30); // You'd really want 3000
}
}
// Displays the given message by adding a paragraph element to the page
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
p {
padding: 0;
margin: 0;
font-family: sans-serif;
}
Well, you are running your while before the timeout happens. Try this
<html>
<head>
<script type="text/javascript">
function funkcija_polnac(i)
{
document.getElementById("output").innerHTML = i + "%";
if (--i > -1) {
setTimeout(function () { funkcija_polnac(i); }, 3000);
}
}
</script>
</head>
<body>
<div style="margin: 0px auto;" onclick="funkcija_polnac(5)">Start</div>
<div id="output"></div>
</body>
</html>

Write sequence of random numbers in javascript to paragraph

Really a newbie question but I can't seem to find the answer. I need to have this html file show a bunch of random numbers, separated by 1 second intervals. For some reason (maybe obvious) it is only showing me the last one unless I have 1 alert after each random number generated. How can I correct this?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var randomnumber
var message
function placePossibleWinner()
{
randomnumber=Math.floor(Math.random()*11);
message="Teste ";
message=message.concat(randomnumber.toString());
document.getElementById("WINNER").innerHTML=message;
//alert(".")
}
</script>
</head>
<body>
<script type="text/javascript">
function runDraw()
{
var i=1
alert("start")
while (i<20)
{
setTimeout("placePossibleWinner()",1000)
i++
}
}
</script>
<h1>H Draw</h1>
<p id="WINNER">Draw</p>
<p></p>
<button onclick="runDraw()">Get me winner!</button>
</body>
</html>
Thanks in advance for any answers/comments.
The problem is all your setTimeouts are being triggered at the same time. Adding alerts pauses the JavaScript execution, so you see each number. Without that, after 1 second, all 19 setTimeouts run (one after another) and you just see one number (the screen is updated so fast, you just see one).
Try using setInterval instead.
function runDraw() {
var i = 1;
var interval = setInterval(function(){
if(i < 20){
placePossibleWinner();
i++;
}
else{
clearInterval(interval);
}
}, 1000);
}​
This will run the function once every second, until i is 20, then it will clear the interval.
I believe you want setInterval instead. using setTimeout in a loop will just queue up 20 calls immediately and they will all fire at once 1 second later. Also, you are setting the innerHTML of the p which will overwrite any previous text.
function placePossibleWinner() {
// add a var here, implicit global
var randomnumber=Math.floor(Math.random()*11);
// add a var here, implicit global
message="Teste " + randomnumber + '\n'; // new line
document.getElementById("WINNER").innerHTML += message; // concat, don't assign
}
function runDraw() {
var counter = 1;
var intervalID = setInterval(function () {
if (counter < 20) {
placePossibleWinner();
counter++;
} else {
clearInterval(intervalID);
}
}, 1000);
}
You are resetting your message in your functions and you are calling placePossibleWinner() the wrong way... you want to use setInterval. Below is a modification of your html/javascript
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var randomnumber;
var message = "Teste ";
var timesCalled = 0;
var funtionPointer;
function placePossibleWinner()
{
timesCalled++;
randomnumber=Math.floor(Math.random()*11);
message=message.concat(randomnumber.toString());
document.getElementById("WINNER").innerHTML=message;
if (timesCalled > 20)
{
clearInterval(functionPointer);
}
}
</script>
</head>
<body>
<script type="text/javascript">
function runDraw()
{
var i=1
alert("start")
functionPointer = setInterval(placePossibleWinner,1000)
}
</script>
<h1>H Draw</h1>
<p id="WINNER">Draw</p>
<p></p>
<button onclick="runDraw()">Get me winner!</button>
</body>
</html>
To start with,
setTimeout("placePossibleWinner()",1000)
should be
setTimeout(placePossibleWinner,1000)
The parameter to setTimeput should be a reference to a function. See JavaScript,setTimeout

how to disappear an animated gif with javascript

i have this code and would like to have an animated gif to disappear after 3 seconds. i learned that i need to add window.onload=loadingGif(); to ensure the 'loadingGif' function is fired when the page loads. i stll have the problem that this code is not working how it should do. i would like to know what is going wrong with that? thanks.
i´m sorry i posted the wrong code. it must be:
<body>
<script type="text/javascript">
var counter = 3;
function downcount() {
document.getElementById('digit').firstChild.nodeValue = counter ;
if (counter == 0 ) {
document.getElementById('loading').style.display = 'none';
document.getElementById('msg').style.display = 'block';
} else {
counter--;
window.setTimeout('downcount()', 1000);
}
}
window.onload=downcount;
</script>
<div id="loading">
<img src="loading/loading40.gif"/>
</div>
<div id="msg" style="display:none">
<?PHP echo $_SESSION['msg'];?>
</div>
Close the img tag.
Also, where's digit? If that doesn't exist then you'll be getting JS errors.
You're doing three 1s setTimeout to wait for 3 seconds? Here is a simpler solution, right out of my head...
window.onload = setTimeout(removeImg, 3000)
var removeImg = function() {
document.getElementById('loading').style.display = 'none'
document.getElementById('msg').style.display = 'block'
}

javascript clearTimeout not clearing timeout!.. this shouldn't be hard?

I'm working on a auto logout using setTimeout and clearTimeout. Should be really straight forward but the clear timeout doesn't seem to stop the timeout and the function is called anyway. I have it set up that the session variable populates a text input that the javascript then reads and compares to the time now. if the difference is more than or equal to 20 seconds an overlay div shows giving an option to renew the session or it will logout in 10 seconds. The script that check the last activity auto runs every ten seconds. Obviously once I've got it working the timings will be longer - these are just for testing purposes.
I have trawled the web but can't seem to find an obvious solution as it not so complicated and looks like it really should just work!
Here's my code:
var t = 0;
function check_status(){
var time_now = Math.floor(new Date().getTime() / 1000);
var last_activity = document.getElementById("last_activity").value;
var since_last_activity = time_now-last_activity;
console.info(since_last_activity);
if(since_last_activity >= 20){
// show div
document.getElementById("logout_warning").style.height = document.documentElement.clientHeight+"px";
document.getElementById("logout_warning").style.display = 'block';
// start countdown
var t = setTimeout("logout();", 10000);
}
}
function logout(){
document.getElementById("logout_warning").style.display = 'none';
location.href="/user/logout";
}
function renew(){
clearTimeout(t);
var time_now = Math.floor(new Date().getTime() / 1000);
document.getElementById("last_activity").value = time_now;
document.getElementById("logout_warning").style.display = 'none';
}
setInterval('check_status()', 10000);
and then in the body...
<div id="logout_warning" style="display:none; width:100%; height:500px; top:0px; left:0px; position:absolute; background-image:url('/images/overlay.png'); z-index:100000;">
<div style="width:300px; position:relative; margin:200px auto; border:1px solid #000000; background-color:#FFFFFF; padding:10px; text-align:center;">
You're going to be logged out in 10 seconds! oh no!<br/><br/>
<button type="button" onclick="renew();">Click here</button> to renew your session
</div>
</div>
The last activity variable is pulled from a text input that is populated by a session variable. This bit seems to work, as in when you click the renew button the value of the input is changed and the console output shows that the time since last activity has been reset.
I hope this makes sense. Please ask for clarification but I'm really stumped on this one!
Thanks!
You have two ts.
var t = 0;
This one in the outside scope.
var t = setTimeout("logout();", 10000);
This one in the inside scope.
clearTimeout(t);
This is reading the one on the outside scope.
Remove the var from the one on the inside scope.
That's because you're redefining the variable in the function and it becomes local to that function, the global t is still 0:
var t = setTimeout("logout();", 10000);
remove the var before the variable!
You're overshadowing the global variable t with a local one:
var t = 0;
function check_status() {
var t = setTimeout("logout();", 10000);
// ^^^^
}
function renew() {
clearTimeout(t);
}
Remove the var to make t refer to the global variable.

Categories