Show div for 15 seconds then show another div - javascript

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.

Related

Javascript: Countdown by animation.width()

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>";
}

How can i add a div based on TIME using js or jquery?

I want to create a timer that will add or remove divs ( inline divs ) based on time function in Javascript or Jquery.
E.g With each second i want to add a div or remove a div.
Can i get some ideas on this?
<html>
<head>
<title>Testing</title>
<script>
var i = 0;
var myVar=setInterval(function () {myTimer()}, 1000);
function myTimer()
{
document.getElementById('Container').innerHTML += "<div id='"+i+"'>This is the Div with New ID 'i'</div>";
i++;
}
</script>
</head>
<body>
<div id='Container'>
</div>
</body>
</html>
This Should Create a DIV each second inside the Div with id 'Container'
Use setInterval.
var diff = 1000, // how long between adds in milliseconds
totalTime = 0, // how long we have run
maxTime = 1000*60*60*5, // how long we want to run
interval = setInterval(function() {
$(".parentDiv").append($("<div>new div</div>"));
totalTime += diff; // keep track of all of our time
if (totalTime >= maxTime) {
clearInterval(interval);
}
},diff);
Note that the time is in milliseconds.
And to get rid of it
clearInterval(interval);
Beware that it will keep running, and if any of your actions take too long or slow down, you could find yourself with quite the mess stumbling over each other.
You can make use of setTimeout(function, mili seconds)
var testTimer;
function timer()
{
// Do your stuff
testTimer = setTimeout("timer()",1000);
}
This will call your timer function every one second. and you can do your stuff in this function
To stop this timer function you can do
window.clearTimeout(testTimer);

setTimeout function not working

This is a basic timer from 01:00 to 00:00 and when it gets to 00:00 I want to show an alert that Time is up.
JsFiddle
To run faster I choose the second 58.
In firebug I see that jocsecunda1 and jocsecunda2 have these values, but I don't know why setTimeount is not triggered. Maybe I am putting it in the wrong place?
Thanks!
//just create html, ignore:
var pentruminut = document.createElement('span');
document.body.appendChild(pentruminut);
pentruminut.setAttribute('id','unminut');
document.getElementById('unminut').innerHTML="01:00";
window.onload=function(){
(function(){
setInterval(function(){
cro();
document.getElementById('unminut').innerHTML="0"+jocminut+":"+jocsecunda1+jocsecunda2;
},1000);
}());
}
var jocminut = 1;
var jocsecunda1 = 6;
var jocsecunda2 = 10;
function cro(){
if(jocsecunda1!=0||jocsecunda2!=0){
jocsecunda2 -=1;
while(jocminut==1){
jocminut-=1;
jocsecunda1 -=1;
}
while(jocsecunda2==-1){
jocsecunda1-=1;
jocsecunda2=9;
}
}
}
//here is the issue:
(function(){setTimeout(function(){
if (jocsecunda1==5&&jocsecunda2==8){
alert("Time is up");
}
},1000);}())
Your setTimeout is set to run only once, with a 1000 millisecond timeout, so the check for 58 seconds is made only once when the timer is at 59 seconds.
A better solution would be to change the way your program works, and instead check when your variables jocsecunda1 == 5 and jocsecunda2 == 8, and fire the alert then.
Example fildde: http://jsfiddle.net/L7u26/4/

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>​

How to show first message on form load and next one after 1min?

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.

Categories