How to reset stop watch for multiple stop watch time? - javascript

I am trying to use multiple stop watch timer by using anchor tag.I have successfully done but I am not able to add a functionality like if I clicked first timer,It will start timer from zero,when I clicked second one,first timer's value will be zero and second one will start timer from zero.I am giving my working code below :
JS:
var digit=0;
var hrs = 0;
var min=0;
var time;
var timer_is_on=0;
var id;
function timer(id){
//[Old] - this should be placed after you increment digit
// document.getElementById("secs").innerHTML = digit
//alert("I am testing value"+id);
//[New]
// get the numerical value for seconds,minutes,hours
digit = parseInt(document.getElementById("secs"+id).innerHTML);
min = parseInt(document.getElementById("mins"+id).innerHTML);
hrs = parseInt(document.getElementById("hrs"+id).innerHTML);
// increment;
digit=digit+1;
if(digit>"59"){
min = parseInt(min)+1;
// why is this code here
var count = min.toString().length;
digit=0;
}
// [old] checking if second is greater than 59 and incrementing hours
// if(digit>"59"){
// [new] check if minute is greater than 59
if(min > "59"){
hrs=parseInt(hrs)+1;
digit=0;
min=0; // minute should be reset as well
}
// set the values after all processing is done
document.getElementById("secs"+id).innerHTML = format(digit);
document.getElementById("mins"+id).innerHTML= format(min);
document.getElementById("hrs"+id).innerHTML=format(hrs);
}
function activate(id){
if(!timer_is_on){
timer_is_on=1;
// time = setTimeout("timer()",1000) will only call it once , use setInterval instead
time=setInterval("timer("+id+")",1000);
}
else {
timer_is_on=0;
clearInterval(time); // clear the timer when the user presses the button again and reset timer_is_on
}
return id;
}
// left pad zero if it is less than 9
function format(time){
if(time > 9)
return time;
else return "0"+time;
}
And The HTML code I have used are :
Click here to start the timer
<span id="hrs1" >00</span>:<span id="mins1" >00</span>:<span id="secs1">00</span></strong>
<br/>
Click here to start the timer
<span id="hrs2" >00</span>:<span id="mins2" >00</span>:<span id="secs2">00</span>
Here is my working js fiddle demo : http://jsfiddle.net/EPtFW/1/

as you are using same method activate() to start second timer, it will make first timer as zero if timer already running.
Solution is "you have to maintain multiple unique timer ids for multiple timers"
For Example, let's say you have T1 and T2 timers to start time;
var timerMap={};
timerMap[createUniqueId for T1] = setInterval();
timerMap[createUniqueId for T2] = setInterval();
to clear timers
clearInterval(timerMap[createUniqueId for T1]);
clearInterval(timerMap[createUniqueId for T2]);
In your case, you have to have createUniqueId and adding to timerMap should be in activate() method. they will work independently.

Related

Update Element at every 10th Second, i.e., like at 12:30:10, 12:31:10, etc

The question: How to update element at every 10th Second, i.e., like at 12:30:10, 12:31:10, etc
The following technically works and does as I need, but how am I supposed to do this in the right way? That is, optimally, in terms of code and execution time?
setInterval(function(){
var now = new Date();
if (now.getSeconds() == 10) {
$('#jama').load('jama.php');
}
},1000);
The Problem: I think what you're asking is: To check every for every tenth second, i.e., 12:30:10 is a tenth second, but check every ten seconds (12:30:13, 12:30:23, etc.) is not.
The Solution: In that case, use setTimeout(), running it every second, to find the tenth second, and when you find the tenth second, then just setInterval() as you're doing now.
The Advantage: What's the advantage? Once you find the tenth second, you can change setInterval()'s delay from 1000 to 60000, since we know the next tenth second will be 60 seconds away. This reduces how often the code needs to check, and it also removes the now() object and the unnecessary checking.
The Code: Working demo below.
var myinterval = false;
function findTenthSecond() {
if(!myinterval) {
findTenthSecond_async();
}
}
function findTenthSecond_async() {
setTimeout(function(){
var now = new Date();
console.log("Check second: " + now.getSeconds() + "|");
if (now.getSeconds() == 10) {
myinterval = true;
// your code is here
setInterval(function(){
console.log ("Load jama.php");
$('#jama').load('jama.php');
},60000); // updated the second count to 60 seconds
} else {
findTenthSecond();
}
}, 1000);
}
findTenthSecond();

setInterval in a countdown timer gets executed multiple times after first round

Hope y'all staying safe
i'm trying to figure out a simple countdown timer with these codes below:
what happens is first time i click it it goes fine, counting down the number by seconds as how it should work. however from second time it becomes "faster", it goes 2 numbers per second. 3rd time it goes 3 numbers per second, or if i clicked it a few times at once it also goes "faster"
I assume its because the interval is adding up (somehow?) and execute the same code n* times per
second. but i don't know where /how i should clear the interval completely each time?
hope this make sense to you guys
and thanks in advance for help
function makeTimer(){
document.getElementById("button-1").innerHTML = "Stop Countdown";
timeLeft = document.getElementById("set-time").value;
// buttonChange()
document.getElementById("set-time").value = ""
setInterval(function(){
if(timeLeft <=0){
clearInterval(timeLeft = 0)
}
document.getElementById("timer-id").innerHTML = timeLeft+"s"
timeLeft = timeLeft - 1
},1000)
}
function toggleTimer(){
// clearInterval(timeLeft)
button = document.getElementById("button-1")
if(button.innerHTML ==='Click to countdown'){
makeTimer()
}else if(button.innerHTML=== "Stop Countdown"){
clearInterval(timeLeft = 0)
button.innerHTML = "Click to countdown"
}
}
You're using clearInterval incorrectly.
setInterval returns a reference to your timer, which you then have to pass to clearInterval to stop it.
Example:
var myTimer = setInterval(myFunction, 1000); //Starts the timer
clearInterval(myTimer); //Stops the timer

Javascript Second Counter

On my website, I am trying to count (and display) how many seconds (not minutes or hours) the user has been on my site. So, if they have been on it for 5 minutes, it will display 300, Not 5 minutes.
I am Very Unexperienced with JavaScript, So please help.
You can use the setInterval function to run another function as often as you choose. For example:
var seconds = 0;
var el = document.getElementById('seconds-counter');
function incrementSeconds() {
seconds += 1;
el.innerText = "You have been here for " + seconds + " seconds.";
}
var cancel = setInterval(incrementSeconds, 1000);
<div id='seconds-counter'> </div>
If you run this snippet, you'll see the counter working.
The setInterval function takes two parameters:
the function you want to call
the number of milliseconds between calls
Since you want to call increment the counter every second, you want to use 1000 milliseconds (1 second).
For more details, see the MDN documentation for setInterval.
My answer is similar to the one above but I'll give it anyway. This will only work on a single page so hopefully your site already runs on AJAX.
window.setInterval((function(){
var start = Date.now();
var textNode = document.createTextNode('0');
document.getElementById('seconds').appendChild(textNode);
return function() {
textNode.data = Math.floor((Date.now()-start)/1000);
};
}()), 1000);
You've been on this page for <span id=seconds></span> seconds.

Simple javascript counter no frills, just count

I have the number 3,453,500 it needs to increase by +1 every 4 seconds.
Need to keep the formatting the same (commas in the right place)
(also is there a way that this can count continuously without the refreshing to the lowest number on page refresh?)
Should be pretty simple...
Retrieve the number from local storage and display it
var num = +localStorage.getItem('num') || 3453500;
document.getElementById('display').innerHTML = num.toLocaleString();
Setup an interval to update the number every 4 seconds, save it and display it
setInterval(function() {
num++;
document.getElementById('display').innerHTML = num.toLocaleString();
localStorage.setItem('num', num);
}, 4000);
JSFiddle

Specific textarea behaviour related to setTimeout

what I am trying to do is give the user a textarea (with enabled input) and allow him to write up to 10 chars. Actually, the textarea should ALLOW more chars, not only 10, and the other chars would behave accordingly:
1º There is a setTimeout whenever the user is on the 11ºchar. So, I'm writing something there, I reach the char number 10º (the "maximum" allowed of text) and want that other char to be erased AFTER a given time.
somethinge = 10 chars.
anotherwor = 10 chars.
input: somethingeiefjaiehf
after 5 seconds:
input: somethinge
input: anotherwordtotestthisandseeifitworks
after 5 seconds:
input: anotherwor
2ºTo accomplish this I basically attached a clearTimeout to a global variable:
//Function "countChar(val)" is activated with the keydown event
var timer_to_op = null;
function countChar(val) {
var len = val.value.length; //lenght of input in textarea
clearTimeout(timer_to_op);
//...
//irrelevant code
//...
}else if(len > 140){
$("#status_toOp_num").text(145-len);
timer_to_op = setTimeout(function(){
val.value = val.value.substring(0, 140);
},5000);
}
Actually, for some reason, it won't work. If the user is typing AND he types another char within the 5 seconds then I want the timer to restart.
input: anotherwor
input: anotherword (+d) timer = 1...2...3...
input: anotherworde (+e) timer = 1...2...
input: anotherwordef (+f) timer = 1...2...3...4...5!
input: anotherwor the user took more than 5 seconds so it erased the excedent.
Hope I got my point through. Any ideas on this one? Thank you very much! (I didn't put any html, it's only <textarea onclick="countChar(this)"> )
I didn't really try to understand what you are doing in your code, seems unnecessarily complicated.
Check this fiddle out. http://jsfiddle.net/Q2h5f/
HTML
<textarea id="limitText">0123456789</textarea>
Javascript
var tarea = document.getElementById("limitText");
tarea.onkeypress = checkInputText;
var timer = null;
function checkInputText(e) {
if (timer) clearTimeout(timer);
timer = setTimeout(limitTextLength, 5000);
}
function limitTextLength() {
var tareaVal = document.getElementById("limitText").value.toString();
if (tareaVal.length > 10) {
tarea.value = tareaVal.slice(0, 10);
}
}
Should solve your issue.

Categories

Resources