timer using javascript - javascript

I want implement timer using java script.I want to decrement timer with variation of interval.
Example.Suppose my timer starts at 500 .
I want decrement timer depending on the level such as
1. 1st level timer should decrement by 1 also decrement speed should be slow.
2.2nd level timer should decrement by 2 and decrement speed should be medium
3.3rd level timer should decrement by 3 and decrement speed should be fast
I can create timer using following code:
<script type="text/javascript">
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time)
{
TotalSeconds=Time;
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer();
setTimeout("Tick()", 1000);
}
function Tick() {
TotalSeconds -= 10;
if (TotalSeconds>=1)
{
UpdateTimer();
setTimeout("Tick()", 1000);
}
else
{
alert(" Time out ");
TotalSeconds=1;
Timer.innerHTML = 1;
}
}
But i call this CreateTimer() function many times so its speed is not controlling because i call it many times.

Couple of points:
You've used all global variables, it's better to keep them private so other functions don't mess with them
Function names starting with a captial letter are, by convention, reserved for constructors
The function assigned to setTimeout doesn't have any public variables or functions to modify the speed while it's running so you can only use global variables to control the speed. That's OK if you don't care about others messing with them, but better to keep them private
The code for UpdateTimer hasn't been included
Instead of passing a string to setTimeout, pass a function reference: setTimeout(Tick, 1000);
Anyhow, if you want a simple timer that you can change the speed of:
<script>
var timer = (function() {
var basePeriod = 1000;
var currentSpeed = 1;
var timerElement;
var timeoutRef;
var count = 0;
return {
start : function(speed, id) {
if (speed >= 0) {
currentSpeed = speed;
}
if (id) {
timerElement = document.getElementById(id);
}
timer.run();
},
run: function() {
if (timeoutRef) clearInterval(timeoutRef);
if (timerElement) {
timerElement.innerHTML = count;
}
if (currentSpeed) {
timeoutRef = setTimeout(timer.run, basePeriod/currentSpeed);
}
++count;
},
setSpeed: function(speed) {
currentSpeed = +speed;
timer.run();
}
}
}());
window.onload = function(){timer.start(10, 'timer');};
</script>
<div id="timer"></div>
<input id="i0">
<button onclick="
timer.setSpeed(document.getElementById('i0').value);
">Set new speed</button>
It keeps all its variables in closures so only the function can modify them. You can pause it by setting a speed of zero.

Hope, this could be helpful:
<html>
<head>
<script type="text/javascript">
function showAlert()
{
var t=setTimeout("alertMsg()",5000);
}
function alertMsg()
{
alert("Time up!!!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Start" onClick="timeMsg()" />
</form>
</body>
</html>

Check this demo on jsFiddle.net.
HTML
<div id="divTimer">100</div>
<div id="divDec">1</div>
<div id="divSpeed">100</div>
<input id="start" value=" Start " onclick="javaScript:start();" type="button" />
<input id="stop" value=" Stop " onclick="javaScript:stop();" type="button" /><br/>
<input id="inc" value=" Increase " onclick="javaScript:increase();" type="button" />
<input id="dec" value=" Decrease " type="button" onclick="javaScript:decrease();"/>​
JavaScript
var handler;
function start() {
handler = setInterval("decrementValue()", parseInt(document.getElementById('divSpeed').innerHTML, 10));
}
function stop() {
clearInterval(handler);
}
function decrementValue() {
document.getElementById('divTimer').innerHTML = parseInt(document.getElementById('divTimer').innerHTML, 10) - parseInt(document.getElementById('divDec').innerHTML, 10);
}
function increase() {
document.getElementById('divDec').innerHTML = parseInt(document.getElementById('divDec').innerHTML, 10) + 1;
document.getElementById('divSpeed').innerHTML = parseInt(document.getElementById('divSpeed').innerHTML, 10) + 200;
stop();
decrementValue();
start();
}
function decrease() {
document.getElementById('divDec').innerHTML = parseInt(document.getElementById('divDec').innerHTML, 10) - 1;
document.getElementById('divSpeed').innerHTML = parseInt(document.getElementById('divSpeed').innerHTML, 10) - 200;
stop();
decrementValue();
start();
}​
Hope this is what you are looking for.

Related

Pause and start JS countdown timer

I am trying to develop a centurion countdown timer for my website. It is a drinking game.
The way the timer works is: It is a 60 second countdown timer. Everytime the timer hits 0 it will +1 a shot counter and restart. It will do this 100 times.
The game is you must do 1 shot, every minute for 100 minutes. I am a beginner at JS and I am learning a lot, but I am seriously struggling to get this to work the way I want it to.
All I need is a "Start" Button, a "Pause" button and a "Reset" button but I can't seem to find a way to make these buttons work without messing the timer up.
Here is the HTML code:
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="Start" onclick="timer()">
<input type="button" value="Pause" onclick="clearInterval(myTimer)">
</div>
and here is the JS code:
var seconds = 60;
var shots = 0;
var timer;
var c = 60;
function timer() {
timer = setInterval(myTimer, 1000)
}
function myTimer() {
document.getElementById("seconds").innerHTML = --c;
if (c == 0) {
shots = shots + 1;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}
If anyone could help me and show me what I am doing wrong and how I can make the code better, please do!
First, consider renaming either your method timer() or variable timer to disambiguate between the two.
Next, setInterval() returns an interval ID, which you store in timer.
clearInterval() takes the interval ID as the parameter, so try passing it the timer variable instead of myTimer (a function)
Little bit clean up needed. For clearInterval, u have to id of timer to clear
var seconds = 60;
var shots = 0;
var timer;
var c = 60;
function start() {
clearInterval(timer)
timer = setInterval(( ) =>{
updateUi()
}, 1000);
}
function pause() {
clearInterval(timer)
}
function updateUi() {
document.getElementById("seconds").innerHTML = --c;
if (c == 0) {
shots = shots + 1;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="Start" onclick="start()">
<input type="button" value="Pause" onclick="pause()">
</div>
You can also use Pub Sub model, to make code looks clean.
var seconds = 60;
var shots = 0;
var c = 60;
function Emitter() {
this.cb;
this.on = cb => {
this.cb = cb;
};
this.emit = () => {
this.cb && this.cb();
};
this.cancel = () => {
this.cb = null;
};
}
const emitter = new Emitter();
const tick = () => {
setInterval(() => {
emitter.emit();
}, 1000);
};
tick()
function start() {
emitter.on(updateUi);
}
function pause() {
emitter.cancel();
}
function updateUi() {
document.getElementById("seconds").innerHTML = --c;
if (c == 0) {
shots = shots + 1;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="Start" onclick="start()">
<input type="button" value="Pause" onclick="pause()">
</div>
<div class="inner">
<h1 class="heading alt">Centurions Timer</h1>
<p>1 Shot. Every Minute. 100 Minutes.</p>
<p>___________________________________</p>
<div id="timer">
<p id="minutes">100</p>
<p id="seconds">60</p>
<p id="shots">0</p>
</div>
<input type="button" value="START" onclick="start()">
<input type="button" value="PAUSE" onclick="pause()">
<input type="button" value="RESET" onclick="reset()">
</div>
Changed the onclick functions to something more meaningful. Added an extra button and some more logic to auto-stop when hitting the 100 minutes.
var seconds = 60,
minutes = 100,
shots = 0;
timer = "";
// this will just stop the timer, if you click start it will resume from where it left off
function pause() {
clearInterval(timer);
}
// resets seconds/minutes/shots, stops game
function reset() {
clearInterval(timer);
seconds = 60;
minutes = 100;
shots = 0;
timer = "";
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML = c;
document.getElementById("shots").innerHTML = shots;
}
// starts game from wherever it was left
function start() {
timer = setInterval(function() {
document.getElementById("seconds").innerHTML = c--;
if (c === 0) {
document.getElementById("minutes").innerHTML = --minutes;
// when 100 minutes are up, game will stop and reset
if (minutes === 0) {
reset();
}
shots++;
c = 60;
}
document.getElementById("shots").innerHTML = shots;
}, 1000)
}

How to make an auto clicker in JavaScript?

I'm currently making a clicker game and I wanted to know how to make a button that when I click on it, a number slowly goes up with intervals. I don't really know how to do the intervals and I've tried doing loops but loops are instant and have no intervals.
var number = 0;
function increase() {
for (var i = 0; i < 1; i++) {
document.getElementById("number").innerHTML = number += 1
}
}
<button onclick="increase()">
by 1
</button>
<div>
number:
<div id="number">
0
</div>
</div>
Can someone turn this into an auto clicker? as said above, i just want to click on the button once and have the value of the variable "number" go up. Thanks.
Here is mine showing how to
use an interval
use eventListener (unobtrusive coding)
clear the interval
how to increment a number and change speed
how to use data attributes
how to use classes and querySelector
var number = 0,
increment = 1,
speed=1000, // one second
tId;
function inc() {
clearInterval(tId); // stop anything already running
tId = setInterval(function() {
document.getElementById("number").innerHTML = number += increment;
}, speed);
}
function changeSpeed() {
speed = +this.getAttribute("data-speed"); // get attribute and convert to number
inc();
}
window.addEventListener("load", function() { // when page has loaded
document.querySelectorAll(".start").forEach(function(but) {
but.addEventListener("click", function() {
increment = +this.getAttribute("data-inc") ; // get from button and convert to number
inc()
});
});
document.getElementById("stop").addEventListener("click", function() { // when clicking
clearInterval(tId);
});
document.querySelectorAll(".speed").forEach(function(but) {
but.addEventListener("click", changeSpeed);
});
});
<button type="button" class="start" data-inc="1">By 1</button>
<button type="button" class="start" data-inc="10">By 10</button>
<button type="button" class="speed" data-speed="1000">One a sec</button>
<button type="button" class="speed" data-speed="500">Two a sec</button>
<button type="button" id="stop">Stop</button>
<div>
number: <span id="number">0</span>
</div>
function increase() {
setInterval(() => document.getElementById("number").innerHTML = number += 1, 1000)
}
setInterval() will call an anonymous function which increment the number each second (1000 ms) until you call clearInterval()
var number = 0;
function increase () {
number++;
document.getElementById('number').innerHTML = number;
}
Try this out.
I believe the issue is, you're not actually incrementing the variable 'number'. What you're instead doing is setting the content of the element number to number +=1;
So since number is 0;
it will only ever show 1 on the HTML.
If you want the number to increment by one automatically after you've clicked the button once. Create a setInterval.
setInterval(() => {
increase()
}, 5000) // increase every 5 seconds
You can set an interval with setInterval();
var number = 0;
function increase() {
for (var i = 0; i < 1; i++) {
document.getElementById("number").innerHTML = number += 1
}
}
setInterval(increase, 1000);
This should increase the number every second.
If you want to stop it then you can say:
var interval = setInterval(increase, 1000);
clearInterval(interval);
var number = 0;
function increase() {
for (var i = 0; i < 1; i++) {
document.getElementById("number").innerHTML = number += 1
}
}
<button onclick="increase()">
by 1
</button>
<div>
number:
<div id="number">
0
</div>
</div>
var number = 0,
increment = 1,
speed=1000, // one second
tId;
function inc() {
clearInterval(tId); // stop anything already running
tId = setInterval(function() {
document.getElementById("number").innerHTML = number += increment;
}, speed);
}
function changeSpeed() {
speed = +this.getAttribute("data-speed"); // get attribute and convert to number
inc();
}
window.addEventListener("load", function() { // when page has loaded
document.querySelectorAll(".start").forEach(function(but) {
but.addEventListener("click", function() {
increment = +this.getAttribute("data-inc") ; // get from button and convert to number
inc()
});
});
document.getElementById("stop").addEventListener("click", function() { // when clicking
clearInterval(tId);
});
document.querySelectorAll(".speed").forEach(function(but) {
but.addEventListener("click", changeSpeed);
});
});
<button type="button" class="start" data-inc="1">By 1</button>
<button type="button" class="start" data-inc="10">By 10</button>
<button type="button" class="speed" data-speed="1000">One a sec</button>
<button type="button" class="speed" data-speed="500">Two a sec</button>
<button type="button" id="stop">Stop</button>
<div>
number: <span id="number">0</span>
</div>
You can use setInterval(function(){ /* do something every 3 seconds */ }, 3000);
You can call the function in the interval parameter or write the code inside.
You can look at these examples.

Javascript timer not working..

Here is my code, please tell me where I've made a mistake so I can learn from it and hopefully get it working :).
Here is the html:
<input type="text" id="txt" />
<input type="button" value="Start Timer" onclick="startTimer()" />
And here is the javascript:
var Timer = 120;
var checkTimer = false;
var t;
function countDown(){
doucment.getElementById("txt").value = Timer;
Timer--;
t = setTimeout("countDown();", 1000);
}
function startTimer(){
if(!checkTimer){
checkTimer = true;
countDown();
}
else{
console.log("Error!");
}
}
Looking into your code in this Fiddle
Had me stumble across a few things,
The startTimer() in the onclick wasn't found.
doucment !== document as pointed out by Sterling Archer
The string eval could be changed to t = setTimeout(countDown, 1000); also pointed out by Sterling Archer
Now let's go to the solution.
HTML
<input type="text" id="txt" />
<!-- Removed the onclick attribute and added an ID for the eventListener -->
<input type="button" value="Start Timer" id="start" />
JS
//Event listener for the button. Same as the onClick, this one, however, does work.
document.getElementById("start").addEventListener("click", startTimer, false);
var Timer = 120;
var checkTimer = false;
var t;
function countDown() {
document.getElementById("txt").value = Timer;
Timer--;
t = setTimeout(countDown, 1000);
}
function startTimer() {
if (!checkTimer) {
checkTimer = true;
countDown();
} else {
console.log("Error!");
}
}
What I've done is:
I've added an event listener to counter the startTimer() "cannot be found" error
I've changed doucment to document
and I've changed your string eval to t = setTimeout(countDown, 1000);
Hope this helps!
You have a typo. You should have document.getElementById("txt") not doucment.getElementById("txt"). Try this:
var Timer = 120;
var checkTimer = false;
var t;
function countDown() {
document.getElementById("txt").value = Timer;
Timer--;
t = setTimeout("countDown();", 1000);
}
function startTimer() {
if (!checkTimer) {
checkTimer = true;
countDown();
} else {
console.log("Error!");
}
}
Update:
If you would like for the timer to stop at zero, you will need to add an if statement to see if the timer is greater than 0 before decrementing the timer again. That would look like this:
HTML:
<input type="text" id="txt" />
<input type="button" value="Start Timer" onclick="startTimer()" />
JS:
var Timer = 120;
var checkTimer = false;
var t;
function countDown() {
document.getElementById("txt").value = Timer;
if (Timer > 0){
Timer--;
}
t = setTimeout("countDown();", 1000);
}
function startTimer() {
if (!checkTimer) {
checkTimer = true;
countDown();
} else {
console.log("Error!");
}
}
Demo: https://jsfiddle.net/hopkins_matt/moks2oyb/
Further improvements could be made to this code, but this is meant to illustrate that your code will work once the errors are fixed.

Timer JavaScript not running in Chrome & Mozilla when window minimized

Hi I am using a Java Script timer, it works well in IE but in Chrome when the window is minimized it becomes too slow, in Mozilla it stops it timer. Can anyone suggest anything ? My code is as follows :-
<html>
<head>
<script>
var millisec = 0;
var seconds = 0;
var timer;
function display(){
if (millisec>=9){
millisec=0
seconds+=1
}
else
millisec+=1
document.d.d2.value = seconds + "." + millisec;
timer = setTimeout("display()",100);
}
function starttimer() {
if (timer > 0) {
return;
}
display();
}
function stoptimer() {
clearTimeout(timer);
timer = 0;
}
function startstoptimer() {
if (timer > 0) {
clearTimeout(timer);
timer = 0;
} else {
display();
}
}
function resettimer() {
stoptimer();
millisec = 0;
seconds = 0;
}
</script>
</head>
<body>
<h5>Millisecond Javascript Timer</h5>
<form name="d">
<input type="text" size="8" name="d2">
<input type="button" value="Start/Stop" onclick="startstoptimer()">
<input type="reset" onclick="resettimer()">
</form>
</body></html>
You can not use setTimeout to make a reliable time keeping script.
John Resig explains how JavaScript timers work: http://ejohn.org/blog/how-javascript-timers-work/
The short version is that there is always have a small delay. The millisecond parameter you pass to setTimeout is a "best effort".
If you want to show a live timer consider polling the time really often. If the event loop slows down, there is no effect on your ability to track time, you just get less updates.
http://jsfiddle.net/64pcr7pw/
<script type="text/javascript">
var timer, time = 0, start_time = 0;
function startstoptimer() {
if (timer) {
time += new Date().getTime() - start_time;
start_time = 0;
clearInterval(timer);
timer = null;
} else {
start_time = new Date().getTime();
timer = setInterval(function () {
document.d.d2.value = time + new Date().getTime() - start_time;
}, 10);
}
}
function resettimer() {
time = 0;
start_time = new Date().getTime();
document.d.d2.value = "0";
}
</script>
<form name="d">
<input type="text" size="8" name="d2"/>
<input type="button" value="Start/Stop" onclick="startstoptimer()"/>
<input type="reset" onclick="resettimer()" />
</form>

Onclick reset setInterval

<!DOCTYPE html>
<html>
<head>
<script>
function timer(x) {
if (x == 1) {
//reset timer
}
var i = 0;
var timer = setInterval(function() {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 500);
}
</script>
</head>
<body>
<p id="demo">hello</p>
<button type="button" onclick="timer(0)">change</button>
<button type="button" onclick="timer(1)">reset</button>
</body>
</html>
I want to reset timer onclick . e.g. if setIntervaltime is set to 5 sec and 3 seconds are elapsed ,after that if some on click on reset button it should start gain from 5 seconds.How to do this.
Keep the return value of setTimeout somewhere that you can get it again (currently you are storing it in a local variable, so it goes away when the function ends)
Call clearTimeout(timer);
Call setTimeout with whatever arguments you want again.
As already Quentin mentioned, use clearInterval to solve your problem.
Wrap it within an if.else.. statement like
if(x == 1) {
clearTimeout(timeout);
}
else {
timeout = setInterval..... // otherwise even after resetting
// it will continue to increment the value
}
Complete Code:
var timeout; // has to be a global variable
function timer(x) {
var i = 0;
if (x == 1) {
clearTimeout(timeout);
document.getElementById("demo").innerHTML = i;
} else {
timeout = setInterval(function () {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 1000);
}
}
JSFiddle

Categories