In the head section:
var countdownTimer; <br/>
countdownTimer = 45; <br/>
function makeCountdown() { <br/>
countdownTimer = countdownTimer - 1; <br/>
}
setInterval(makeCountdown, 1000);
<br/><br/>
In the body section of the page:
document.write(countdownTimer);<br/>
function updateCountdown() { <br/>
document.replace(countdownTimer); <br/>
}
<br/><br/>
setInterval(updateCountdown, 1000);
<br/><br/>
I've checked in the browser console and the countdownTimer variable goes down each second, but where I'm struggling is on how to update the variable on the page in real time.
I've had a long look and I can't find anything here or elsewhere online that can help me out, I'm also fairly new to javascript. Many thanks for any help!
Make changes to the Element rather than document itself
There is no replace method for document
There is no point having 2 intervals if duration is identical
Note: Make sure you place script as last child of body or else, DOM api will try toa ccess the element before DOM is ready which will return null result for document.getElementById('elem')
var countdownTimer;
var elem = document.getElementById('elem');
countdownTimer = 45;
function makeCountdown() {
countdownTimer = countdownTimer - 1;
elem.textContent = countdownTimer;
}
setInterval(makeCountdown, 1000);
elem.textContent = countdownTimer;
<span id='elem'><span>
A little addition to Rayon's answer. To stop countdown when timer reach 0
var timer=45;
var intervalId;
function countdown(){
$('#elem').text(timer);
if(timer==0){
clearInterval(intervalId);
}
timer--;
}
intervalId=setInterval(countdown,1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<span id="elem"></span>
Related
I want to display the loading time of a webpage on site. I can get this working by writing to console.log but writing the information to a page is beyond me.
In my head I have
<!-- Loading Time -->
<script type="text/javascript">
var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;
</script>
Then I have this to write to the console log
<script type="text/javascript">
window.onload = function () {
var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart;
console.log('Page load time is '+ loadTime / 1000);
}
</script>
This works perfectly but I really want to display the loading time on a webpage. How do I achieve this? My page is a simple html / css site.
Three possible methods are:
Just writing to the document directly (should not be used because of the reasons described here):
document.write(loadTime);
Adding an HTML element and setting its inner text to loadTime:
function displayLoadtime(loadtime){
document.getElementById("loading-time").innerText = loadtime;
}
<p id='loading-time'>Loading...</p>
Creating the element in Javascript and displaying the loadTime using it:
function displayLoadingtime(loadtime){
let p = document.createElement("p");
p.innerText = loadtime;
document.getElementById("loading-time-container").appendChild(p);
}
<div id='loading-time-container'></div>
I know what I answered is some beginners' stuff and you probably know it, but I will edit the answer in case you give more details, because I don't see any problems in displaying it if you already have the loadTime.
You can write the time you calculated into an element of the webpage using the innerText property of a Node.
window.onload = function() {
var loadTime = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart;
console.log('Page load time is ' + loadTime / 1000);
performanceDisplay = document.getElementById("performance-display") // get a reference to the paragraph
performanceDisplay.innerText = loadTime / 1000 // put the value of the variable loadTime into the paragraph
}
<body>
<p id="performance-display"></p>
</body>
Or, if you do not want to put the paragraph manually into the HTML, you can create it in the JavaScript using document.createElement:
window.onload = function() {
var loadTime = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart;
console.log('Page load time is ' + loadTime / 1000);
performanceDisplay = document.createElement("p") // create a new paragraph element
performanceDisplay.innerText = loadTime / 1000 // put the value of the variable loadTime into the paragraph
document.body.appendChild(performanceDisplay) // add the paragraph element to the body of the document
}
Welcome to StackOverflow, Rylad!
You can easily put it into your webpage by referencing an HTML element.
Ie. add an element with the id timeContainer to your page and set its innerHTML to your variable, loadTime. Here's an example:
<body>
<span id="timeContainer">
The load time will be displayed here when the page is finished loading
</span>
<script type="text/javascript">
window.onload = function() {
var loadTime = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart;
console.log(loadTime)
document.getElementById("timeContainer").innerText = loadTime;
}
</script>
</body>
Try this,
Simple way to get loading time
<body>
<span id="loadingTime"></span>
<script>
window.addEventListener('load', (e) => {
let timestemp = new Date(e.timeStamp).getTime()
console.log('loading time is', timestemp)
document.getElementById('loadingTime').innerText = "loading time is "+timestemp
})
</script>
</body>
I am trying to make an idle game rather like candy box. I will have a number at the side of the page which rises by one every second. However, the code shown below does not seem to be working. Could anyone tell me why it is not working; how to fix it and where they got their info from. Thank you in advance.
<script type="text/javascript">
var i = 0;
function increment(){
i++;
document.getElementById('money').innerHTML = i;
}
setInterval(increment(), 1000);
</script>
<h2><u>The best game of the century</u></h2>
<p>you have £<span id="money"></span>.</p>
</body>
</html>
You have two issues:
You are calling your script before the DOM is rendered, so at the point the script runs, there is no element with ID of money.
In your setInterval call, you only need the function name (increment) without the parentheses. Including the parentheses (as increment()) only calls the function at that specific moment, rather than referencing it to be called at each interval. (See the Microsoft page on setInterval for more detailed information.)
See this code:
<h2><u>The best game of the century</u></h2>
<p>you have £<span id="money"></span>.</p>
<script type="text/javascript">
var i = 0;
function increment() {
i++;
document.getElementById('money').innerHTML = i;
}
setInterval(increment, 1000);
</script>
change setInterval(increment(), 1000); to setInterval(increment, 1000);
Its not working because as per document https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
it takes a function reference to be executed.. but calling the function increment() like this will only execute once and the return of that function will be used which will be null and not intended hope this clears it
var i = 0;
function increment(){
//console.log(i);
i++;
document.getElementById('money').innerHTML = i;
}
setInterval(increment, 1000);
<h2><u>The best game of the century</u></h2>
<p>you have £<span id="money"></span>.</p>
I found this JS-Countdown Script at JSFiddle.
EDIT:
I'm using the code of rafaelcastrocouto now, which is nearly perfect. I wanted a 10-seconds JQuery Countdown-Script with an interval that resets the countdown timer at 5 seconds and starts over again and again, but only for a specific class with a specific id on the whole HTML page. If it drops to 0, the countdown should stop. Also I want to reset specific counters to 10.
It's about a WebSocket that refreshes every second and depending on the data I get for specific counters I want to reset them or they should count down to zero.
New JSFiddle: http://jsfiddle.net/alexiovay/azkdry0w/4/
This is how I solved with jquery and native setInterval...
var setup = function(){
$('.count').each(eachSetup);
};
var eachSetup = function(){
var count = $(this);
var sec = count.data('seconds') ;
count.data('count', sec);
};
var everySecond = function(){
$('.count').each(eachCount);
};
var eachCount = function(){
var count = $(this);
var s = count.data('count');
count.text(s);
s--;
if(s < 0) {
s = count.data('seconds');
}
count.data('count', s);
};
setup();
setInterval(everySecond, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="count" data-seconds="5"></p>
<p class="count" data-seconds="10"></p>
<p class="count" data-seconds="15"></p>
You have sever errors in code, e.g.
setTimeout(cd_go(id), 1000); - should point to function reference not to function execution. setTimeout also returns the timeout id. You must past that id to clearTimeout
clearTimeout(this); it should take id instead of global object (window) or undefined if you are working in strict mode
loop = setInterval(function(id) { … } - id points to undefinded as you are not passing any value for it
It's a simple exercise in which I want to hide a link I put in my Html file.
But make it appear after a timer has run out in my function.
This is the javascript bit
(below is the html bit)
var i = 10;
var time;
var countdown = document.getElementById("countdown");
var link = document.getElementById("link");
function MyFunction3() {
document.getElementById("imageoef").style.visibility="visible";
link.style.visibility="hidden";
i--;
countdown.innerHTML= i;
time = setTimeout ("MyFunction3();",1000);
if (i < 1) {
countdown.innerHTML="";
document.getElementById("imageoef").style.visibility="hidden";
link.style.visibility="visible";
}
}
HTML
<img src="images/loading.gif" alt="Loading..." id="imageoef" style="visibility:hidden" />
<form method="post">
<input onclick="MyFunction3();" type="button" value="start download" />
</form>
<div id="countdown">
<a id="link" href="http://freelanceswitch.com/freelance-freedom/freelance-freedom-2/" >Your download is ready!</a>
</div>
HTML:
<input type="button" onclick="hideLink()" value="Start" />
<p id="timer"></p>
<a id="link" href="">This link is hidden for 10 seconds.</a>
JavaScript:
var timeLeft = 10;
var count;
window.hideLink = function hideLink()
{
document.getElementById("link").style.visibility = "hidden";
count = setInterval (decrementTimer, 1000);
setTimeout (showLink,1000 * timeLeft);
};
function decrementTimer()
{
timeLeft = timeLeft - 1;
document.getElementById("timer").innerHTML = timeLeft + " seconds";
if(timeLeft <= 0)
{
window.clearInterval(count);
document.getElementById("timer").style.visibility = "hidden";
}
}
function showLink()
{
document.getElementById("link").style.visibility = "visible";
}
http://jsfiddle.net/rPnNr/4/
If you have place the javascript in the header section your code may not work. Because you are storing the countdown and link element value at the page loading. At that time if your elements has not get loaded to the page your countdown and link vars going to be null. better thing is access your elemet after your button click.
var i = 10;
var time;
var countdown = document.getElementById("countdown");
var link = document.getElementById("link");
function MyFunction3() {
countdown = document.getElementById("countdown");
link = document.getElementById("link");
document.getElementById("imageoef").style.visibility="visible";
link.style.visibility="hidden";
i--;
countdown.innerHTML= i;
time = setTimeout ("MyFunction3();",1000);
if (i < 1) {
countdown.innerHTML="";
document.getElementById("imageoef").style.visibility="hidden";
link.style.visibility="visible";
}
}
Your code doesn't work because it sets the countdown div's innerHTML to '', but the link was inside that div, so gets deleted and you can't then make it reappear just by setting its visibility. You could fix it just by putting the link outside of the div in the HTML.
<img src="images/loading.gif" alt="Loading..." id="imageoef" style="visibility:hidden"
/>
<form method="post">
<input id="myInput" type="button" value="start download" />
</form>
<div id="countdown">
</div><a id="link" href="http://freelanceswitch.com/freelance-freedom/freelance-freedom-2/">Your download is ready!</a>
While I was at it I altered your script a bit... (jsfiddle)
var i = 10,
time;
function E(id) {return document.getElementById(id) }
E('myInput').onclick = function () {
E('imageoef').style.visibility = 'visible';
E('link').style.visibility = 'hidden';
time = setInterval(function () {
i--;
E('countdown').innerHTML = i;
if (i < 1) {
clearInterval(time);
E('countdown').innerHTML = '';
E('imageoef').style.visibility = 'hidden';
E('link').style.visibility = 'visible';
}
}, 1000);
}
Actually the other changes are all non-essential but some explanation anyway:
you ideally want 2 functions, not just 1 - the first to trigger the countdown and the second for each time the counter decreases
setInterval is more useful than setTimeout here, as it recurs automatically and you don't need to keep setting it; however you do then need to use clearInterval to stop the timer. In your original code you were doing nothing to stop the timer so it would just carry on indefinitely (but with the effects hidden).
I preferred to set onclick in javascript rather than having an onclick attribute of the html tag. But your original method does also work.
(Here is your original code with only the necessary changes to make it work.)
Hi i am using Javascript set timeout to run a certain function.
How do i display the last 10 seconds of the timeout when it is nearing the end?
var a = setTimeout('someFunction()', 10000);
Is it able to display something using the value that it store into the variable?
Thanks
I have created a small demo for you,
http://jsfiddle.net/praveen_prasad/DYaan/1/
<div id="target" style="display:none">
target
</div>
var target,
allotedTimeForWork=100 /*you can change this*/
;
var handler = setTimeout(function(){
if(!target)
{
target=document.getElementById('target');
}
target.style.display="block";
startTicker();
}, allotedTimeForWork);
function startTicker()
{
var counter=10;
var tickerHandler= window.setInterval(function(){
if(counter>0)
{
//cache target
target.innerHTML="you have "+counter +" seconds left";
counter--;
}
else
{
target.innerHTML="time over";
clearInterval(tickerHandler);
}
},1000);
}
It is not possible to directly get the remaining time of a Timeout.
You could either try to make multiple Timeouts for every second, or have another variable where you store when the Timeout was started.
I would use two timeouts.
The first with time minus 5 seconds, that calls a function with the second timeout (5 seconds) which would have the timer displayed.
Take a look here: http://jsfiddle.net/VCAnm/
HTML:
<span id="aaa">10</span>
JavaScript:
setInterval(function() {
var elem = document.getElementById('aaa');
elem.innerHTML = elem.innerHTML - 1;
}, 1000);
set 2 timers one for the timeout and another for the warning
var warn_time = 5000;
var function_name = 'someFunction()';
var a = setTimeout('warnFunction(function_name, warn_time)', 10000 - warn_time);
function warnFunction(function_name, time) {
alert('only ' + time + ' seconds left'); //use a div or whatever to display
var b = setTimeout(function_name, time);
}