At the moment I am creating an on screen timer in javascript. This is the code for my timer:
var i = 30;
function startTimer() {
var countdownTimer = setInterval(function() {
console.log(i);
i = i - 1;
if (i < 0) {
clearInterval(countdownTimer);
}
}, 1000);
}
I am just wondering where I should place my document.getElementById("time-remaining").innerHTML = "Time Remaining:" + i;
I am also wondering if the above document.getElementById is correct (will it be displayed as a onscreen timer or will it fail or something)?
Thanks in advanced.
Try this:
var i = 30;
function startTimer() {
var countdownTimer = setInterval(function () {
console.log(i);
i = i - 1;
if (i < 0) {
clearInterval(countdownTimer);
return; //This will prevent -1 to be written to html
}
document.getElementById("time-remaining").innerHTML = "Time Remaining:" + i;
}, 1000);
}
startTimer();
Dont forget to call the function.
Demo: http://jsfiddle.net/GCu2D/842/
You can put the
document.getElementById("time-remaining").innerHTML = "Time Remaining:" + i;
After the startTimer function or really anywhere.
And yes thedocument.getElementById is correct, if your html id is the same one as in javascript.
Related
So I'm trying to get a function to run once every second, and then after four seconds I want it to stop using clearInterval()
function dotdotdot(){
var x = 0;
setInterval(function(){
if (x>=3){
torpWri = torpWri + ".";
document.getElementById("torpTxt").innerHTML = torpWri;
x++;
}
else{
x = 0;
clearInterval();
}
},1000);
}
This is my function and it should stop after four seconds and then reset x to 0 for when I call it again.
function loadButton(){
torpWri = "Torpedo Loading"
if(torpLoadAmount[arNum]<5){
torpLoadAmount[arNum]++;
torpAmount--;
document.getElementById("torpCnt").innerHTML = torpAmount;
document.getElementById("torpTxt").style.visibility = "visible";
document.getElementById("butunload").disabled=true;
document.getElementById("butfire").disabled=true;
document.getElementById("torpTxt").innerHTML = torpWri;
dotdotdot();
}
else{
document.getElementById("torpTxt").style.visibility = "visible";
document.getElementById("torpTxt").innerHTML = "Torpedo Bay Full";
}
timer3();
}
This is how I'm calling it.
I'm just needed to know why it isn't running the function dotdotdot(); every second and then stopping after four. Then when I call it again it should all just reset. But it's not running...
I've been searching for a while and haven't found anything, so I came here.
(Also, please don't comment on my other code, I know there are probably easier ways to do it, but this is what I'm working with right now.)
setInterval returns a timerID, which needs to be passed to clearInterval.
var ticks = 0;
var intervalID = setInterval(function() {
if (++ticks == 4) {
clearInterval(intervalID);
}
}, 1000);
You could also use setTimeout instead, and just not schedule a new tick when the condition is met.
setTimeout(function callback(ticks) {
if (ticks > limit) {
return;
}
setTimeout(callback, 0, ++ticks);
}, 1000, 0)
You need to store the handle / intervalId for the interval when it is set and then use it when you want to clear the interval:
function dotdotdot(){
var x = 0;
var intervalId = -1;
intervalId = setInterval(function(){
if (x>=3){
torpWri = torpWri + ".";
document.getElementById("torpTxt").innerHTML = torpWri;
x++;
} else {
x = 0;
clearInterval(intervalId);
}
},1000);
}
More info: https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Timers
setInterval will return a timerid. So do like
var timer = setInterval(fun......)
Then
clearInterval(timer)
How can we repeatedly update the contents of a div using setInterval
I am using the question from this link as a reference How to repeatedly update the contents of a <div> by only using JavaScript?
but i have got few questions here
Can we do it without anonymous functions,using closures. I have tried but could not end up with any workable solution.
How can we make it run infinitely, with the following code it gets stopped once i reaches 10.
window.onload = function() {
var timing = document.getElementById("timer");
var i = 0;
var interval = setInterval(function() {
timing.innerHTML = i++;
if (i > 10) {
clearInterval(interval);
i = 0;
return;
}
}, 1000);
}
<div id="timer"></div>
I am confused about setIntervals and closures
can some one help me here
Thanks
You could do something like this with a closure. Just reset your i value so, you will always be within your given range.
window.onload = function() {
var updateContent = (function(idx) {
return function() {
if (idx === 10) {
idx = 0;
}
var timing = document.getElementById("timer");
timing.innerHTML = idx++;
}
})(0);
var interval = setInterval(updateContent, 1000);
}
<div id="timer"></div>
This one should be clearer.
function updateTimer() {
var timer = document.getElementById("timer");
var timerValue = parseInt(timer.getAttribute("data-timer-value")) + 1;
if (timerValue == 10) {
timerValue = 0;
}
timer.setAttribute("data-timer-value", timerValue);
timer.innerHTML = "the time is " + timerValue;
}
window.onload = function() {
setInterval(updateTimer, 1000);
}
<div id="timer" data-timer-value="0"></div>
As a java script beginner, I wanted to try my hand at writing stop watch code and I wrote the following:
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts a stopwatch:</p>
<p id="demo"></p>
<button id="start-stop" onclick="myTimerFunction()">Start time</button>
<button id="resetter" style="visibility:hidden" onclick="resetTimer()">Reset</button>
<script>
var timer = new Object();
timer.hours = 0;
timer.minutes = 0;
timer.seconds = 0;
timer.milliseconds = 0;
timer.add = add;
function add() {
timer.milliseconds+=10;
if(timer.milliseconds == 1000) {
timer.seconds++;
timer.milliseconds = 0;
}
if(timer.seconds == 60) {
timer.minutes++;
timer.seconds = 0;
}
if(timer.minutes == 60) {
timer.hours++;
timer.minutes = 0;
}
}
timer.display = display;
function display () {
var str = "";
if(timer.hours<10) {
str += "0";
}
str += timer.hours;
str += ":";
if(timer.minutes<10) {
str += "0";
}
str += timer.minutes;
str += ":";
if(timer.seconds<10) {
str += "0";
}
str += timer.seconds;
str += ":";
/*var x = timer.milliseconds/10;
if(x < 10) {
str += "0";
}*/
if(timer.milliseconds<10) {
str += "0";
}
if(timer.milliseconds<100) {
str += "0";
}
str += timer.milliseconds;
return str;
}
timer.reset = reset;
function reset() {
timer.hours = 0;
timer.minutes = 0;
timer.seconds = 0;
timer.milliseconds = 0;
}
var myVar;
function start() {
timer.add();
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = timer.display() + "\t" + t;
}
function stop() {
clearInterval(myVar);
}
function resetTimer() {
stop();
timer.reset();
document.getElementById("demo").innerHTML = timer.display();
document.getElementById("start-stop").innerHTML="Start time";
document.getElementById("resetter").style.visibility="hidden";
}
function myTimerFunction() {
var x = document.getElementById("start-stop");
if(x.innerHTML.match("Start time")) {
document.getElementById("resetter").style.visibility="visible";
myVar = setInterval(function(){start()},10);
x.innerHTML="Stop time";
}
else if(x.innerHTML.match("Stop time")) {
stop();
x.innerHTML="Start time";
}
}
</script>
</body>
</html>
But, the problem is when I put the delay in setInterval(func,delay) as 1 and doing corresponding changes, it is not giving reliable timing for seconds. It is slower than a normal clock. It gives 'kind of' reliable timing for delay >= 10.
I checked for stop watch js scripts online but all of them use some or other form of Date() and set "delay" as "50", which I do not understand why, as of now. There is an answer here in SO which doesn't use Date() but it also has the same problem as mine. I could not comment there as I do not have enough reputation so I am asking a question instead.
So, my question is: Is it impossible to achive normal clock reliability, if we don't use Date() function? Else if it is possible, please help me improve this piece of code or please provide some pointers.
Thanks.
Here's how you'd do it without getTime, which you really shouldn't...
var ms = 0;
var intervalID;
function start() {
var freq = 10; // ms
intervalID = setInterval(function () {
ms += 10;
var myDate = new Date(ms);
document.getElementById('watch').innerHTML = myDate.getUTCHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds() +
":" + myDate.getMilliseconds();
}, freq);
}
function stop() {
clearInterval(intervalID);
}
function reset() {
ms = 0;
myDate = new Date(ms);
document.getElementById('watch').innerHTML = myDate.getUTCHours() + ":" + myDate.getMinutes() + ":" + myDate.getSeconds() +
":" + myDate.getMilliseconds();
}
Fiddle
As you've found out setInterval/setTimeout is not reliable. You must use a native time library to get a reliable time.
Since you can't keep the time in JavaScript the idea is that you poll the time, and poll it often so that it looks close enough.
If you naively do:
setInterval(function () {
console.log((new Date()).getTime();
}, 1000); // 1 second
you will see that it will skip seconds.
A better approach is something like:
var last = 0;
setInterval(function () {
var now = Math.floor((new Date()).getTime() / 1000); // now in seconds
if (now !== last) {
console.log(now);
last = now;
}
}, 10); // 10ms
If you want more information as too why JavaScript timers are unreliable, read this great article.
http://ejohn.org/blog/how-javascript-timers-work/
I did 2 countdowns events but I can't stop the setTimeout (countDown) function later using the clearTimeout. This is my jQuery:
$(document).ready(function () {
var lives = 5
var livesmenos1 = "4";
var livesmenos1 = 4;
var countdownfinal = 10;
var t;
var isTimeron = false;
var onelive = "1";
var onelive = 1;
$(".wrongbutton, .wrongbutton2, .wrongbutton3").click(function () {
$(".countdownfirst").text(livesmenos1)
livesmenos1--;
if (livesmenos1 == 0) (livesmenos1 = 0);
if (livesmenos1 < 2)
$(".countdownfirst").css({ "color": "990099", "font-size": "380%" });
if (livesmenos1 < 1)
$(".lives").attr("src", "images/morelives.gif");
if (livesmenos1 < 0)
$("#tableone, #tabletwo").delay(1000).hide(2000);
if (livesmenos1 < 0)
$("#tableloser").delay(2000).fadeIn(2500, function countDown() {
setTimeout(countDown, 1000);
$("#box").text(countdownfinal + " seconds").css({ "color": "990099" });
countdownfinal--;
if (countdownfinal < 1) (countdownfinal = 10);
if (countdownfinal < 2)
$(".countdownfirst").text(onelive++);
if (onelive > 5)
$(".countdownfirst").text("5");
if (onelive > 1)
$("#nextbuttonloser").delay(1000).fadeIn(500).delay(30000);
});
});
});
then I did the myStopFunction onclick button to start the clearTimeOut function:
function myStopFunction()
{
clearTimeout(countDown);
}
and it doesn't work. I tried to trigger also using jQuery but again, with no effect. How can i do to stop the setTimeout function named "countDown"?
thanks
There is no way to stop a specific function from firing in a Timeout. The only way is to stop the timeout itself. Every timeout returns an integer value when it is called. Use this value to clear the timeout. Note that it is going to need to be available to the scope of your function
var TimeoutHandle;
$(document).ready(function () {
...
TimeoutHandle = setTimeout(countDown, 1000);
...
});
function myStopFunction()
{
clearTimeout(TimeoutHandle);
}
I'm trying to implement a script that essentially counts down from 30 seconds to 0, and at 0, redirects to the homepage. However, I noticed that my script only works on Firefox but not Chrome and Safari. On these browsers, the counter remains "stuck" at 30 seconds—never refreshing the HTML, but the redirect works fine. Not sure if I'm doing something wrong or if setInterval is not the right method for this kind of thing.
<script>
var seconds = 31;
var counter = setInterval("timer()", 1000);
function timer() {
seconds = seconds - 1;
if (seconds < 0) {
setTimeout("location.href='http://www.homepage.com';", 100);
return;
}
updateTimer();
}
function updateTimer() {
document.getElementById('timer').innerHTML = "Redirecting in " + " " + seconds + " " + "seconds";
}
</script>
Thanks in advance!
EDIT: So weirdly enough, my code (and all of yours) is working on JSFiddle, but it's just failing to "repaint" the HTMLinner when it's actually rendering the page. The seconds are changing fine (I outputted them to the console), the changes just aren't rendering.
Final Edit: This problem basically resulted from invalid CSS. I believe—the counter was running above the photo and I set the span to relative positioning with a higher z-index and top and bottom elements. I don't believe this is acceptable for something that is not a block.
Here's a working sample:
(function() { // wrapper for locals
var timer = document.getElementById("timer"),
seconds = 5,
counter = setInterval(function() {
if (--seconds < 1) {
clearInterval(counter);
timer.innerHTML = "Redirecting now...";
setTimeout(function() {
location.href = 'http://www.homepage.com';
}, 500);
} else {
timer.innerHTML = timer.innerHTML.replace(/\d+/, seconds);
}
}, 1000);
})();
<div id="timer">Redirecting in 5 seconds</div>
Here is a cleaner implementation with fewer defined functions (with demo):
<span id='timer'></span>
<script>
var seconds = 31;
setInterval(function() {
seconds = seconds - 1;
if (seconds < 0) {
setTimeout(function() {document.getElementById('timer').innerHTML = "redirecting..."}, 100);
return;
}
updateTimer();
}, 1000);
function updateTimer() {
document.getElementById('timer').innerHTML = "Redirecting in " + + seconds + " seconds";
}
<script>
Of course every JavaScript programmer should any opportunity to point out that "eval is evil" which includes passing a string to setInterval and setTimeout :)
Change your function to a variable, that worked for me:
<script>
var seconds = 31;
var counter = setInterval(timer, 1000);
var timer = function() {
seconds = seconds - 1;
if (seconds < 0) {
setTimeout("location.href='http://www.homepage.com';", 100);
return;
}
updateTimer();
}
function updateTimer() {
document.getElementById('timer').innerHTML = "Redirecting in " + " " + seconds + " " + "seconds";
}
</script>