jquery timer implementation - javascript

All,
Is there a jQuery timer which can start a timer for 20 minutes and display time elapsed? Please point me to a small code for it.
var austDay = new getTime();
austDay = new getSeconds(austDay);
var duration = 1200;
duration += austDay;
Thanks

Not sure about a jQuery solution, but it's quite simple to do anyway:
var elapsed = 0;
var interval;
var total = 60 * 20; // 20 mins in seconds
function showElapsedTime()
{
if(elapsed < total)
{
elapsed += 1;
// If you want you can convert the seconds elapsed to minutes and seconds
// here before you display them
$('#elapsed').html(elapsed);
}
else
{
clearInterval(interval);
alert('Done');
}
}
$(function(){
interval = setInterval(showElapsedTime, 1000);
});
Where #elapsed is a div or span element that you want to show the elapsed time in.
There are quite a few timer plugins, but they are all just abstractions of setTimeout and setInterval anyway, and I'm not sure they're really much simpler to use.

Here is an example using the jQuery Timers plugin. You can change it to suit your needs.
$("#start").click(function() {
$("#example_2").everyTime(1000, 'timer2', function(i) {
$(this).text(i);
}, 15);
});
$("#stop").click(function() {
$("#example_2").stopTime('timer2');
});

Are you searching for a plugin like timeX?
Maybe this is what you can use..

Related

setInterval halted when I move between browser tabs in react [duplicate]

function initTimer(timeLeft) {
var Me = this,
TotalSeconds = 35,
Seconds = Math.floor(timeLeft);
var x = window.setInterval(function() {
var timer = Seconds;
if(timer === -1) { clearInterval(x); return; }
$('#div').html('00:' + (timer < 10 ? '0' + timer : timer));
Seconds--;
},1000);
}
I have this code. Everything works fine, when this tab is active in browser, but when I change tab and return in tab later it has problems. To be more precise, it Incorrectly displays the time.
I'd also tried setTimeout, but problem was the same.
One idea, which I have is: HTML5 Web Workers...
But here is another problem... browsers support.
can someone help to solve this problem?
How can I write setInterval, which works properly,even when tab is not active
Use the Date object to calculate time. Don't rely on a timer firing when you ask it to (they are NOT real-time) because your only guarantee is that it'll not fire before you ask it to. It could fire much later, especially for an inactive tab. Try something like this:
function initTimer(periodInSeconds) {
var end = Date.now() + periodInSeconds * 1000;
var x = window.setInterval(function() {
var timeLeft = Math.floor((end - Date.now()) / 1000);
if(timeLeft < 0) { clearInterval(x); return; }
$('#div').html('00:' + (timeLeft < 10 ? '0' + timeLeft : timeLeft));
},200);
}
initTimer(10);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div>
Note that by checking it more frequently we can make sure it's never off by too much.
JavaScript timers are not reliable, even when the tab is active. They only guarantee that at least as much time as you specified has passed; there is no guarantee that exactly that amount of time, or even anything close to it, has passed.
To solve this, whenever the interval fires, note what time it is. You really only need to keep track of two times: the current time, and the time that the previous interval fired. By subtracting the previous tick's time from the current tick's time, you can know how much time has actually passed between the two, and run your calculations accordingly.
Here's a basic outline of how something like this might look:
function initTimer(timeLeft) {
var Me = this,
TotalSeconds = 35,
Seconds = Math.floor(timeLeft),
CurrentTime = Date.now(),
PreviousTime = null;
var x = window.setInterval(function() {
var timer = Seconds,
timePassed;
PreviousTime = CurrentTime;
CurrentTime = Date.now();
timePassed = CurrentTime - PreviousTime;
if(timer < 0) { clearInterval(x); return; }
$('#div').html('00:' + (timer < 10 ? '0' + timer : timer));
Seconds = Seconds - timePassed;
},1000);
}

repeating timer functionality and logic

I'm creating pomodoro timer- interval should repeat with different duration after first one completes. simplified non working exampe:
var firstDuration=5;
var secondDuration=10;
var timer=setInterval(()=>{
firstDuration--
if (firstDuration<0){
clearInterval(timer) ..
//secondDuration-- dont know how to continue..
What is the best way to implement such functionality? Also i plan to use Date.now() rather than -- .
If i've understood the requirements correctly, this will do what you want. It will have a timer go off every second until 20 minutes have elapsed, then every second until 5 minutes have elapsed. At that point it starts over with the 20 minute countdown.
const workDurationSeconds = 20 * 60;
const breakDurationSeconds = 5 * 60;
function startCountdown(session) {
let duration;
if (session === 'work') {
duration = workDurationSeconds;
} else {
duration = breakDurationSeconds;
}
let id = setInterval(() => {
duration--;
if (duration <= 0) {
clearInterval(id);
startCountdown(session === 'work' ? 'break' : 'work');
}
}, 1000);
}

Continuing a cleared setIntervall instead of resetting it

EDIT & UPDATE: for reference I rewrote the whole thing with only 1 timer and a second to time converter. Very clean and less complex. Here is the full code: http://pastebin.com/Hb6cBryL
I got this timer that I built out of javascript: http://powerpoint.azurewebsites.net/
It is quite simple code, but for the final implementation I would need to be able to pause the timer and restart it. I use 2 setIntervalls, 1 for the minutes that triggers every 60s and one for the seconds that triggers every second.
When I pause it I clear the intervals. However when I restart them the minutes restart at the 60 interval and aren't synced with the seconds anymore.
I probably implemented this in a horribly wrong way so I'd like to ask for your advice. 1 idea I had was to continue the inverval but avoid updating the variable and text on the page so that the minutes/seconds stay in sync< However this doesn't sound like an ideal solution to me. All tips are welcome :)
Js code:
var minutes = null, seconds = null, cnt, secs;
function settimer(frm) { if (minutes == null) { cnt = frm.timeinput.value - '1'; secs = '59';} };
function stop() {
clearInterval(minutes);
clearInterval(seconds);
minutes = null;
seconds = null;
document.getElementById("minutes").innerHTML = '00';
document.getElementById("seconds").innerHTML = '00';
}
function pause() {
clearInterval(minutes);
clearInterval(seconds);
}
function runtimer() {
event.preventDefault();
if (minutes == null) {
document.getElementById("minutes").innerHTML = cnt;};
minutes = setInterval(function () {
if (cnt == '0') { stop() } else { cnt -= 1; document.getElementById("minutes").innerHTML = cnt; };
}, 6000);
if (seconds == null) { document.getElementById("seconds").innerHTML = secs; };
seconds = setInterval(function () {
if (secs == '0') { secs = '59' } else { secs -= 1; document.getElementById("seconds").innerHTML = secs; };
}, 100);
}
You'll need to wrap them somehow, and recognise that you can't immediately get the timer's id.
function setIntervalWithOffset(fn, delay, offset) {
var o = {id: null, o_id: null};
o.o_id = window.setTimeout(function () {
o.id = window.setInterval(fn, delay);
}, offset);
return o;
}
function setTimeoutWithOffset(fn, delay, offset) {
var o = {id: null, o_id: null};
o.o_id = window.setTimeout(function () {
o.id = window.setTimeout(fn, delay);
}, offset);
return o;
}
To clear, use window.clearTimeout on obj.o_id and whichever type you set for obj.id.
You should also consider whether you'd be better off implementing a setTimeout loop rather than using setInterval so you don't have a chance of a cascade error
Sorry, I think that you are in a bad way. Why do you want to use two intervals to do the same thing? Intervals are asynchronous, you can not synchronize two intervals that runs independently.
You can achieve that with just one interval. To show seconds, you can just increment another variable each time that your counter reachs a threshold:
var counter = 0;
var seconds = 0;
var $interval = setInterval(function(){
counter++;
if (counter >= 6000) {
counter = counter - 6000;
seconds++;
}
, 10);
So, it will be more easy to stop/restart your interval.
You need to get the handle to the timer, in order to be able to reset it later, you can do like below:
timeoutHandle = setTimeout(function(){/*code*/}, 1000);
clearTimeout(timeoutHandle);
Take a look at this jsfiddle
Taken from : How do I stop a window.setInterval in javascript?

Actionscript 2 Setinterval add milliseconds to timer

I have set my setInterval to 10 seconds. And it all working fine in my game, it count down from 10 seconds and change scene when it hit 0.
The problem is that I really would need to show milliseconds to and I cant understand how I will add it to the counter... It shouldnt be hard at all but I really cant figure it out.
Here is the script:
timer = 10;
clearInterval(countdownInterval);
countdown = function(){
timer--;
if (timer ==0){
gotoAndPlay("Scene 1",2 );
}
}
countdownInterval = setInterval(countdown,1000);
You probably need a Date() object which will report time deltas in milliseconds. Using setTimout to increment a timer is likely to have a number of problems.
var startTime = +(new Date) + (10 * 1000);
var checkFinished = function() {
timeRemaining = startTime - (new Date);
if(timeRemaining <= 0) {
gotoAndPlay("Scene 1",2 );
} else {
setTimeout(checkFinished, 100)l
}
}
setTimeout(checkFinished, 0);

When seconds come x, do something

How I will do that:
When seconds come 31 (example 11:57 31sec.) do somthing, every minute. Using Javasript.
Thanks in advance.
Read the current time, calculate the number of seconds until the next time the seconds is ':31' then use setTimeout with the appropriate delay. You could use something like this:
var atSeconds = 31;
var secondsLeft = atSeconds - new Date().getSeconds();
if (secondsLeft <= 0) secondsLeft += 60;
setTimeout(foo, secondsLeft * 1000);
Remember to call it again in the function foo so that it repeats.
Something like this will probably be as close as you can get.
function initializeInterval() {
while (new Date().getSeconds() < 30);
setInterval(doWork, 60000);
}
function doWork() {
}

Categories