Functionality:
A timer will start counting from 0 seconds and value will increment every 1 second. The timer will continue to increment till it reaches 59 mins 59secs before the timer will stop.
What has been done:
I have set 2 different <div> that will dynamically display the timer value as it is increasing. 1st <div> is for the minute value while the 2nd <div> is for the second value.
While the timer increment is done a setinterval method of 1 second
Issue:
I have tried to append the value of timer to one of the <div> but realise that the minute value of the timer will not be able to be appended to the 1st <div> and the value will only be displayed in the 2nd <div>
Hence, I would like to ask for assistance on how to splice the value of the system timer such that the minute value can be appended and can be displayed in the 1st <div> when the second value can be appended and can be displayed in the 2nd <div>
Code:
var GameTimer = 0;
$("#Game_Elements").fadeIn({
queue: false,
complete: function() {
//Start Game Timer
var SetGameTimer = setInterval(function() {
GameTimer++;
//append timer to timer game elements
$("#Game_Minute_timer").html(GameTimer);
$("#Game_Second_timer").html(GameTimer);
//Check on time, if more than 1hr, automatically navigate to last game page
}, 1000);
}
});
<div id="Game_Elements" style="position:absolute; z-index:7; top:0px; left:0px; width: 1920px; heigth: 1000px; margin:auto;">
<table id="Game_Timer_Element">
<tr>
<td>
<div id="Game_Minute_timer" style="z-index:50; position:absolute; top:609px; left:900px; font-size:90px; font-family:'GothicBold'; width:1080; color:#fff;">
<font face="GothicBold"></font>
</div>
</td>
<td>
<div id="Game_Second_timer" style="z-index:50; position:absolute; top:609px; left:900px; font-size:90px; font-family:'GothicBold'; width:1080; color:#fff;">
<font face="GothicBold"></font>
</div>
</td>
</tr>
</table>
</div>
I think your best bet would be to put the time in one div and use Modulus/Math.floor to do your Minute:Second timer.
Like this:
$("#Game_timer").html(Math.floor(GameTimer / 60) + ":" + GameTimer % 60);
If you want to keep them in separate div's go ahead and stick with the same layout you had, and use
Math.Floor(GameTimer / 60)
for minutes, and
Gametimer % 60
for seconds.
You have only seconds, so you have to split them to minutes and seconds. For example:
var GameTimer = 0;
$("#Game_Elements").fadeIn({
queue: false,
complete: function() {
//Start Game Timer
var SetGameTimer = setInterval(function() {
GameTimer++;
var minutes = ('0' + Math.floor(GameTimer/ 60)).slice(-2);
var seconds = ('0' + (GameTimer - minutes * 60)).slice(-2);
if(minutes < 60){
//append timer to timer game elements
$("#Game_Minute_timer").html(minutes+" : ");
$("#Game_Second_timer").html(seconds);
}
//Check on time, if more than 1hr, automatically navigate to last game page
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Game_Elements" style="">
<table id="Game_Timer_Element">
<tr>
<td>
<div id="Game_Minute_timer" style="">
<font face="GothicBold"></font>
</div>
</td>
<td>
<div id="Game_Second_timer" style="">
<font face="GothicBold"></font>
</div>
</td>
</tr>
</table>
</div>
Related
I am beginner in HTML and I am trying to put a timer in my HTML university project daily word game that shows time left until the next day and word. I found a W3Schools tutorial for a timer but it does not work for me because it is until constant date.
My code looks like this:
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="images/tabIcon.ico">
<title>Daily WordGame</title>
<style>
h1 {
font-family: Tahoma, sans-serif;
text-align: center;
}
p {
font-size: large;
text-align: center;
}
</style>
</head>
<body>
<h1>Welcome to your daily source of educational fun</h1>
<hr>
<p style="font-size: large;">Everyday you have a chance of guessing a different word.
</p>
Go to about
<p>this is a second text</p>
<ul>
<li>Boats</li>
<li>Cars</li>
<ul>
<li>Buggati</li>
<table>
<tr>
<td>Price</td>
<td>Top speed</td>
<td>0-100</td>
<td>Horse Power</td>
</tr>
<tr>
<td>3.300.000$</td>
<td>420km/h</td>
<td>2.2s</td>
<td>1480</td>
</tr>
</table>
<img src="images/car.jpg" style="width: 500px;height:300px;">
</ul>
<li>Trucks</li>
</ul>
</body>
<html>
Add a span or any text element with an id of timer
<span id="timer">Time until next word: </span>
And add JavaScript code to get the countdown
<script>
var now = new Date();
// If you want another time, set it here with javascrip Date API
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var tomorrow = new Date().setDate(now.getDate() + 1);
var timer = document.getElementById("timer");
// Update the count down every 1 second
setInterval(() => {
// Fill in with the time until tomorrow
var time = new Date(tomorrow - now);
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
// Format the time to add a leading 0 if less than 10
function fillZero(n) {
if (n < 10) {
return "0" + n;
} else return n.toString();
}
timer.innerText = "Time until next word: " + "0d " + fillZero(hours) + "h " + fillZero(minutes) + "m " + fillZero(seconds) + "s";
}, 1000);
</script>
So the modified code with your HTML is
<!DOCTYPE html>
<html>
<head>
<link rel="icon" href="images/tabIcon.ico">
<title>Daily WordGame</title>
<style>
h1 {
font-family: Tahoma, sans-serif;
text-align: center;
}
p {
font-size: large;
text-align: center;
}
</style>
</head>
<body>
<h1>Welcome to your daily source of educational fun</h1>
<hr>
<p style="font-size: large;">Everyday you have a chance of guessing a different word.
</p>
Go to about
<p>this is a second text</p>
<span id="timer">Time until next word: </span>
<ul>
<li>Boats</li>
<li>Cars</li>
<ul>
<li>Buggati</li>
<table>
<tr>
<td>Price</td>
<td>Top speed</td>
<td>0-100</td>
<td>Horse Power</td>
</tr>
<tr>
<td>3.300.000$</td>
<td>420km/h</td>
<td>2.2s</td>
<td>1480</td>
</tr>
</table>
<img src="images/car.jpg" style="width: 500px;height:300px;">
</ul>
<li>Trucks</li>
</ul>
<script>
var now = new Date();
// If you want another time, set it here with javascrip Date API
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var tomorrow = new Date().setDate(now.getDate() + 1);
var timer = document.getElementById("timer");
// Update the count down every 1 second
setInterval(() => {
// Fill in with the time until tomorrow
var time = new Date(tomorrow - now);
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
// Format the time to add a leading 0 if less than 10
function fillZero(n) {
if (n < 10) {
return "0" + n;
} else return n.toString();
}
timer.innerText = "Time until next word: " + "0d " + fillZero(hours) + "h " + fillZero(minutes) + "m " + fillZero(seconds) + "s";
}, 1000);
</script>
</body>
<html>
I have this small script. My probme is that when I click the Start button the count starts normally, but if I click it again, the counter starts acting weird. How do I avoid this issue and start a fresh counter on every button click?
$(".c1").click(function(e){
let a = 0;
setInterval(function(){ $("#timer").text(a); a++; }, 500);
})
.card{ font-size:25px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<div class="btn c1"> Start Timer</div>
<br>
<br>
<span id="timer" class="card">0</span>
The "acting weird" is because you're starting a second, separate timer, so now both are running, each putting its own copy of a in the element. You need to remember the previous timer's handle (the return value of setInterval) and cancel it (via clearInterval):
let handle = 0;
$(".c1").click(function(e) {
let a = 0;
clearInterval(handle)
handle = setInterval(function() {
$("#timer").text(a);
a++;
}, 500);
})
.card {
font-size: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<div class="btn c1"> Start Timer</div>
<br>
<br>
<span id="timer" class="card">0</span>
Note I've used the value 0 as the initial value of handle and then I've happily called clearInterval whether the timer was already running or not. 0 is an invalid handle value, and clearInterval (and clearTimeout) ignore invalid handle values, so you can safely do that. But add the if if you like.
You should reset your interval before starting the new one
let interval;
$(".c1").click(function(e) {
let a = 0;
if(interval) clearTimeout(interval);
interval = setInterval(function(){ $("#timer").text(a); a++; }, 500);
})
.card{ font-size:25px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<div class="btn c1"> Start Timer</div>
<br>
<br>
<span id="timer" class="card">0</span>
You have to clear the interval before starting a new one. Else, two things (or more) are incrementing a.
To clear an interval, just call clearInterval on the result of setInterval.
let interval;
$(".c1").click(function(e){
let a = 0;
clearInterval(interval);
interval = setInterval(function(){ $("#timer").text(a); a++; }, 500);
});
.card{ font-size:25px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<div class="btn c1"> Start Timer</div>
<br>
<br>
<span id="timer" class="card">0</span>
every time you click you start another one setInterval
solution
when it has to count from the beginning - use clearInterval
https://stackoverflow.com/a/5978560/3046335
to disable actions if we want to start the counter once - use .attr("disabled", true);
//1
var time = 0
$(".c1").click(function(e){
clearInterval(time); // stop if runn interval
let a = 0;
time = setInterval(function(){ $("#timer").text(a); a++; }, 500);
})
//2
$(".c2").click(function(e){
let a = 0;
setInterval(function(){ $("#timer2").text(a); a++; }, 500);
$(".c2").attr("disabled", true);
})
.card{ font-size:25px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<div class="btn c1"> Start Timer 1</div>
<br>
<br>
<span id="timer" class="card">0</span>
<br>
<br>
<div class="btn c2"> Start Timer 2</div>
<br>
<br>
<span id="timer2" class="card">0</span>
<!DOCTYPE html>
<html>
<head>
<title> Cookie Clicker! </title>
<script type="text/javascript">
var logAt=function(id,message){
document.getElementById(id).innerHTML=message;
};
</script>
</head>
<body>
<h1 class="center" style="text-align:center"> Cookie Clicker </h1>
<p class="center" id="para1" style="text-align:center;"> Keep collecting cookies and start your very own sweet empire!</p>
<p>
<div class="center" id="cookiesPerSecond" style="text-align:center"> </div>
<button id="getACookie" type="button" onClick="getCookie()"><image src="http://blog.speekee.com/wp-content/uploads/2014/09/Cookie.gif"
style="width:300px;height:300px;align:middle"></button>
<h3 id="cookies" style="text-align:center;">Cookies:0 </h3>
</p>
<h2 id="store"> Store</h2>
<p>
<button type="button" onClick="getOven()"> Buy another oven! <image
src="http://products.geappliances.com/MarketingObjectRetrieval/Dispatcher?RequestType=Image&Name=0107108.jpg" style="width:50px;height:50px"> </button>
</p>
<div id="oven"> <strong> 90 Cookies </strong> An extra oven <br> will give you half a cookie <br> per second</div>
<style>
#getACookie{
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
<script type="text/javascript">
var cookies=0;
var cookiesPerSecond=0;
function getCookie(){
cookies+=1;
logAt("cookies","Cookies:"+cookies);
};
var getOven=function(){
if(cookies>=10){
cookies=cookies-90
cookiesPerSecond+=0.5;
logAt("cookiesPerSecond","Cookies per second:"+cookiesPerSecond);
setInterval(function(){
cookies+=cookiesPerSecond;
logAt("cookies","Cookies:"+cookies);},1000);
}
else{
alert("You do not have enough cookies!");
}
};
</script>
</body>
</html>
When getting an oven more than once, (in the "getOven" function) instead of one cookie per second, it adds 2 cookies persecond, and so on. Is this a problem with my variables? What should i do to fix it?
You need to clear the previous intervals before starting a new one. See a modified code example below:
var cookies=0;
var cookiesPerSecond=0;
var interval = null; //Declare a variable to hold a reference to the interval
function getCookie(){
cookies+=1;
logAt("cookies","Cookies:"+cookies);
};
var getOven=function(){
if(cookies>=10){
cookies=cookies-90
cookiesPerSecond+=0.5;
logAt("cookiesPerSecond","Cookies per second:"+cookiesPerSecond);
// Check if a previous interval has been set, if so clear it.
if (interval != null) {
clearInterval(interval);
}
// Finally, set a new interval and store a reference to it in the variable
interval = setInterval(function(){
cookies+=cookiesPerSecond;
logAt("cookies","Cookies:"+cookies);},1000);
}
else{
alert("You do not have enough cookies!");
}
};
I have the simple function of changing content of container div.
There is a <table> inside the container <div>, with 2 <td>s, the javascript simply moves left this <table> and it works, but onclick and I need to execute the moving function with time interval.
<div onclick="move(this.children[0])" class="table_wrap">
<div class="table_scroll" style="left: 0px;">
<table cellpadding="0" cellspacing="5" width="1920px">
<tr>
<td style="background-color: red;">
a
</td>
<td style="background-color: blue;">
b
</td>
</tr>
</table>
</div>
</div>
<script language="javascript">
function move(elem) {
var left = 0
function frame() {
left -= 5; // update parameters
elem.style.left = left + 'px' // show frame
if (left == -965) // check finish condition
clearInterval(id)
}
var id = setInterval(frame, 1) // draw every 10ms
}
</script>
And CSS:
<style type="text/css">
.table_wrap{
position:relative;
overflow:hidden;
width: 967px;
height: 250px;
left: -2px;
top: 5px;
}
.table_wrap .table_scroll{
position: absolute;
text-align:center;
white-space:nowrap;
}
</style>
I tryed to use setInterval, but failed.
http://jsfiddle.net/hqztm2dt/1/ here is the JSfiddle, just click on the red line..
Thanks in advance for the attention !
If you need to move it on interval, see this:
http://jsfiddle.net/gsddsxgy/2/ (here the time interval is 3ms)
html:
<div class="table_wrap">
<div id='move' class="table_scroll" style="left: 0px;">
<table cellpadding="0" cellspacing="5" width="1920px">
<tr>
<td style="background-color: red;">
a
</td>
<td style="background-color: blue;">
b
</td>
</tr>
</table>
</div>
</div>
JS:
setInterval(function(){
var elem=document.getElementById('move');
var left = 0
function frame() {
left -= 5; // update parameters
elem.style.left = left + 'px' // show frame
if (left == -965) // check finish condition
clearInterval(id)
}
var id = setInterval(frame, 1) // draw every 10ms
}, 3000);
If you need to move the div on click but after a little time gap, see
this http://jsfiddle.net/gsddsxgy/
code:
function move(elem) {
setTimeout(function(){
var left = 0
function frame() {
left -= 5; // update parameters
elem.style.left = left + 'px' // show frame
if (left == -965) // check finish condition
clearInterval(id)
}
var id = setInterval(frame, 1) // draw every 10ms
}, 1000);
}
The problem with your code in jsFiddle is the move function isn't defined when trying to call it - if you use addEventListener you can bind the method to the click event using just javascript and not the onClick attribute. Using your code:
var elem = document.getElementById('wrapper');
elem.addEventListener('click', move);
function move() {
var left = 0
function frame() {
left -= 5; // update parameters
elem.style.left = left + 'px' // show frame
if (left == -965) // check finish condition
clearInterval(id)
}
var id = setInterval(frame, 1) // draw every 10ms
}
JS fiddle - http://jsfiddle.net/b1q7poj4/2/
I have three small absolutely positioned divs in my homepage. i want only one div to appear at a time, so that the page should start with only the first div and after 3 seconds, the second div and after 3 seconds the third div and this process should continue infinitely. this is the for-loop I've come up with for doing this 10 times. how can i make the same happen infinitely?
// this for not making infinite loop
var nb_loop=0;
var max_loop=10;
var j=0;
for (var i=2; i<=3 ; i++){
nb_loop++;
j++;
console.log("i="+i+", j="+j); // or alert if you want
if (j>=3)
j=0;
if (i>=3)
i=0;
if (nb_loop>max_loop)
break;
}
JS:
var counter = 1;
function showDiv(){
$('.display').hide();
$('#div'+counter).show();
(counter == 4 ? counter = 1 : counter++)
}
showDiv();
var timer = setInterval(showDiv, 3000);
HTML:
<div id='container'>
<div id='div1' class='display' style="background-color: red;">
div1
</div>
<div id='div2' class='display' style="background-color: green;">
div2
</div>
<div id='div3' class='display' style="background-color: blue;">
div3
</div>
<div id='div4' class='display' style="background-color: yellow;">
div4
</div>
</div>
CSS:
.display { display: none; }
Use Jquery setInterval function use for infinite time
use JQUERY SETTIMEOUT() function
like this
jQuery(document).ready(function () {
//hide a div after 3 seconds
setTimeout(function(){ jQuery("#div").hide(); }, 3000);
});