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);
Related
I created a little timer which runs from 30seconds down to 0 and saved in the localStorage, butthen restarts after a event and again begins at 30secs. But if I open 2 tabs of the same page the code runs double. That means that after 1 seconds the timer jumps for example from 30 to 28.
function timer(){
localStorage.setItem("time", 30);
setInterval(function(){
localStorage.setItem("time", localStorage.getItem("time") - 1);
timerPlace.innerHTML = localStorage.getItem("time");
if(localStorage.getItem("time") < 0){
localStorage.setItem("time", 0);
timerPlace.innerHTML = "TIME TO PLACE !";
}
}, 1000);
if(localStorage.getItem("time") === null){
localStorage.setItem("time", 30);
}
}
I already thought of getting the number of opened tabs and do something with this. Or maybe there is a way to only run a javascript code in one tab.
Store the start time of your count in localStorage. Then calculate the distance from it in seconds. when reach 30, clear that value.
This example is without using localStorage because not allowed in a stack snippet.
var start = (new Date()).getTime();
var ind_id
ind_id = setInterval(function() {
var now = (new Date()).getTime()
var diff_in_seconds = Math.round((now - start) / 1000)
if (diff_in_seconds >= 30) {
cancelInterval(ind_id)
return;
}
timerPlace.innerHTML = (30 - diff_in_seconds)
}, 1000)
<div id="timerPlace"></div.>
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);
}
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);
}
I'm working on a simple project that is HTML and Javascript; and I have a problem with my timer.
I'm calculating the seconds between two Date() objects; and every 2 seconds, I want to get a new random number. I have a setInterval that runs every 100 ms and when I get past the 2 second mark, the code inside the if statement should run.
So my question is:
How can I make sure the code execute only once per 2 seconds in an if statement that is inside a setInterval() that runs every 100 ms?
Here is the code:
var startTime = new Date();
var endTime = new Date();
var randomNumber = 0;
var gameTimer = setInterval(function(){
//calculate seconds;
var secondsPassed = Math.round( (endTime - startTime) / 1000 );
if(modulo(secondsPassed,2) == 0){
//when the "gate" is open this keep executing every 100 mili seconds.
//but i want it to execute only once every 2 seconds.
randomNumber = Math.floor(Math.random()*lanes.length);
$(lanes[randomNumber]).append(box);
}
endTime = new Date();
}, 100);
var modulo = function (n, m) {
var remain = n % m;
return Math.floor(remain >= 0 ? remain : remain + m);
};
I think you are asking for a double-interval timer.
var interval = 100, beat = 2000, ticks = 0;
var timer = setInterval(function(){
runsEvery100ms(); // ««« Code here runs every 100 ms.
if (ticks > 0 && ticks % beat === 0) {
runsEvery2000ms(); // ««« Code here runs every 2000 ms.
ticks = 0;
}
ticks += interval;
}, interval);
Demo Fiddle here.
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..