This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Javascript: find the time left in a setTimeout()?
I'm trying to use setTimeout() as a way of pausing a series of events in JS.
Here's an example of what I'm doing and what I'd like to do in comments - http://jsfiddle.net/8m5Ww/2/
Any suggestions how I can populate var timeRemaining with the total milliseconds remaining in var a?
You can't get directly the timer remaining seconds.
You can save in a variable the timestamp when the timer is created and use it to calculate the time to the next execution.
Sample:
var startTimeMS = 0; // EPOCH Time of event count started
var timerId; // Current timer handler
var timerStep=5000; // Time beetwen calls
// This function starts the timer
function startTimer(){
startTimeMS = (new Date()).getTime();
timerId = setTimeout("eventRaised",timerStep);
}
// This function raises the event when the time has reached and
// Starts a new timer to execute the opeartio again in the defined time
function eventRaised(){
alert('WOP EVENT RAISED!');
clearTimer(timerId); // clear timer
startTimer(); // do again
}
// Gets the number of ms remaining to execute the eventRaised Function
function getRemainingTime(){
return timerStep - ( (new Date()).getTime() - startTimeMS );
}
This is custom sample code created "on the fly".
Not possible, but if you set the contents of a separate var to the time you set it, you can easily figure it out manually.
Related
This question already has an answer here:
Are there any standards for mobile device web browsers in terms of thread sleeping? [closed]
(1 answer)
Closed 8 years ago.
I'm developing a chronometer app in Tizen and I'm currently using the setInterval function to schedule the next time the text with the numbers will be updated:
chrono : function() {
SecondsChrono += 1;
},
setInterval(chrono(), 1000);
But when the device's screen is put on "sleep mode" the chronometer gets delayed.
I want to know if anyone has experienced this and if you have some way to avoid it or if you have any advice for me to implement this chronometer in another way.
You should use setInterval only to update the screen, to see how much time has ellapsed since the chronometer first started you should do something like this:
var SCREEN_UPDATE_REFRESH_RATE= 1000;
var startTime= (new Date()).getTime();
var updateScreen= function() {
var currentTime= (new Date()).getTime();
var timeEllapsed = currentTime - startTime; //this value is in milliseconds
document.write("Ellapesed time in seconds: " timeEllapsed / 1000);
setTimeout(updateScreen, SCREEN_UPDATE_REFRESH_RATE);
}
updateScreen();
It is better to use setTimeout in this case than setInterval. The difference between the two is that setInterval schedules the function to execute forever every X milliseconds while setTimeout schedules to execute once and then never again, in this case the function sets a new timeout that keeps the updating process forever. If your user system is overloaded various setInterval callbacks can be chained together which can freeze the user browser. See this for more information.
This question already has answers here:
Call a javascript function at a specific time of day
(4 answers)
Closed 9 years ago.
I've been developing a web app, and I was wondering if there is a way to display a model at a specific date/time.
In the app, the user can book task or reminders, so when I read from the database the task a specific I want to schedule the display of the modal at the date/time specify by the user.
For instance, the user book a task for 2013-09-23 at 14:00 and I want to display a message in the modal.
I kwon we can set time interval with the JavaScript:
setInterval(function () {
showModal();
}, 10 * 1000);
But how to specify an hour like in the sample?
In that setInterval call, 10 * 1000 means 10 times 1000 milliseconds, or in other words 10 seconds. If you want an hour, it's just a bigger number. 1000 * 60 * 60 is an hour.
However, setInterval is for running a function multiple times. Unless you wanted it to be called every hour, you are probably looking for setTimeout instead. setTimeout schedules a function to be run once after the time period expires.
You can try like this.
Make your setInterval() to run for a continues time.
Compare the date, by converting them to milliseconds. and a comparison condition.
setInterval(function () {
var date = new Date("2013-09-23 14:00");
var schDateSecs = Date.parse(date);
var currentDate = new Date();
var schCurrentSecs = Date.parse(currentDate);
if (schDateSecs == schCurrentSecs) {
//execute
showModal();
}
}, 10 * 1000);
Thank you all for your answers, they help me come up with a solution:
function setNotification(notificationDate, notificationCallback){
var currentDate = new Date();
var date = new Date(notificationDate);
var interval = date - currentDate;
if(interval > 0)
window.setTimeout(function(){ notificationCallback(item)}, interval); //notificationCallback = showModal()
}
I have a problem trying to know if a setInterval() is taking place or it was killed.
I am creating an interval and saving it into a variable:
interval = setInterval('rotate()',3000);
Then on click to an element I stop the interval and wait 10 seconds before starting a new one, by the way the variable interval is global:
$(elm).click(function(){
clearInterval(interval);
position = index;
$('#banner div').animate({
'margin-left':position*(-img_width)
});
setTimeout('startItnerval()',10000);
});
function startItnerval(){
interval = setInterval('rotate()',3000);
}
It seems to work but eventually I can realize that there are intervals still being in place, everytime I start a new interval it is saved in the interval variable, which is global, so in theory even if I start 100 intervals they are all saved in the same variable replacing the previous interval right? So I should only have one instance of interval; then on clearInterval(interval); it should stop any instance.
After looking at the results, apparently even if it is saved in the same variable, they are all separate instances and need to be killed individually.
How can I trace how many intervals are being executed, and if possible identify them one by one? even if I am able to solve the problem I really would like to know if there is a way to count or show in the console how many intervals are being executed?
thanks
jsFiddle Demo
As pointed out in comments, the id's constantly increase as timers are added to a page. As a result, it may be possible to clear all timers running on a page like this:
function clearTimers(){
var t = window.setTimeout(function(){
var idMax = t;
for( var i = 0; i < idMax; i++ ){
window.clearInterval(i);
window.clearTimeout(i);
}
},4);
}
The reason that you can only see one interval is because every time you start a new interval, you overwrite the value in interval. This causes the previous intervals to be lost but still active.
A suggestion would be to just control access to your variable. Clearly there is an issue where the start function is called too often
clearInterval(interval);//when you clear it, null it
interval = null;
and then take advantage of that later
if( interval != null ){
interval = setInterval('rotate()',3000);
}
Also, as Pointy noted in a comment, using a string to call a function is not best practice. What it basically does is converts it into a Function expression which is similar to using eval. You should probably either use the function name as a callback
setInterval(rotate,3000);
or have an anonymous function issue the callback
setInterval(function(){ rotate(); },3000);
setInterval returns an Id, not the actual object, so no, no interval will be overriden if you repeat the line
var xy = setInterval(function() {...}, 1000);
If you want to stop the interval you have to clear it:
clearInterval(xy);
And if your startInterval can be called multiple times in a row, but you don't want to create multiple intervals, just clear the inverval before you start a new one:
function startInterval(){
clearInterval(interval);
interval = setInterval('rotate()',3000);
}
If you have to create multiple intervals, you could save the ids in an array to keep track of them:
var arr = [];
//set the interval
arr.push(setInterval(...));
//get number of currently running intervals
var count = arr.length //gives you the number of currently running intervals
//clear the interval with index i
clearInterval(arr[i]);
arr.splice(i, 1);
I am trying to display several count down timers on same page. now as far as i know there are 2 ways of doing it without using jquery plugins or some other scripts (if you know of a good one please let me know)
starting 1 sec setInterval and a global variable that will contain milliseconds and then just reduce -1000 every interval.
creating a function that reduce 1 sec from a global variable and then at the bottom of that function setting a setTimeout of 1 sec that will run that functions so basically recursion every 1 sec.
My question is which of the 2 options will work better and/or faster?
here is demonstrative code for both:
setInterval:
var amount_of_seconds_left = 46800000;
setInterval(function(){
if(amount_of_seconds_left > 1000){
amount_of_seconds_left -= 1000;
}
},1000);
setTimeout:
var amount_of_seconds_left = 46800000;
function startTime(){
if(amount_of_seconds_left > 1000){
amount_of_seconds_left -= 1000;
t=setTimeout(function(){startTime()},1000);
}
}
Both ways could work but i was wondering performance wise which is better and is performance is even an issue with this ?
setInterval and setTimeout don't start after 1000ms e.g. if another script is running, so both can cause delays. It would be better to use the setIntervall to call the display update only and use the the Date object to calculate the exactly remaining time. E.g. after the browser was busy the timer shows the correct time after the next update.
Here an example:
HTML:
<div id="timer1"></div>
<div id="timer2"></div>
javascript:
// update all timer
function updateTimer() {
for (var i in aTimer) {
var oTimer = document.getElementById(aTimer[i].sId);
var iSeconds = parseInt((aTimer[i].iFinished - Date.now()) / 1000);
oTimer.innerHTML = iSeconds;
}
}
// Init all timers with DOM-id and finish time
var aTimer = [
{ sId: 'timer1', iFinished: Date.now() + 46800000 },
{ sId: 'timer2', iFinished: Date.now() + 780000}
];
// call display update
setInterval(function() {
updateTimer();
}, 333);
I belive that the setInterval code executes every 1000ms exactly, while the setTimeout waits 1000ms, runs the function, which takes some ms, then sets another timeout. So the wait period is actually greater than 1000ms.
From this post:
setTimeout or setInterval?
I have the following script in a js file:
// Ad score
var score = 0;
//$('#score').text(score);
function foundMatchingBlocks(event, params) {
params.elements.remove();
score += 100;
$('#score').text(score);
};
Now on each matching, 100 points are added to var score. This all works. Now I want to extend this a bit. As soon as the page loads I want to start a countdown to reduce the number of points (starting with 100) with 1 point a second for 60 seconds. So the minimum number of points a user can get is 40. When someone gets the points, the counter should reset and countdown again.
Example:
Page loads (timer starts from 100)
User has a match after 10 seconds (+90 points are added)
Counter resets and countdown from 100 again
User found a match after 35 sec (+65 points are added)
etc etc
Problem is, I have no idea how to do this :( Hope someone can help me with this.
The above is fixed, thanks all for helping!!!
The big picture is, you'll need to become pretty familiar with timeouts and intervals in javascript. This is the reference page I keep going back to when I need to refresh my memory: http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
For your specific task, you'll probably want to use an Interval that triggers every 1000 milliseconds to calculate the second-by-second point reduction, and a separate Timeout for failure that resets every time the user completes their challenge.
Here are a few tips for working with timeouts and intervals that usually lead to followup questions:
When you set a timeout, always capture the return value (I think it's basically a random integer). Save it to some global var for convenience.
var failureTimer; // global var high up in your scope
failureTimer = setTimeout ( "gameOver()", 100000 ); // 100 seconds * 1000ms
Then in whichever method gets called when the player completes their challenge, you call this:
clearTimeout (failureTimer); // resets the timer and gives them another 100 seconds
failureTimer = setTimeout ( "gameOver()", 100000 ); // yes call this again, to start the 100 sec countdown all over again.
The second pain point you're likely to encounter when working with Timeouts and Intervals is how to pass parameters to the functions like gameOver() in my example above. You have to use anonymous functions, as described here:
Pass parameters in setInterval function
For more on anonymous functions, this is a good overview:
http://helephant.com/2008/08/23/javascript-anonymous-functions/
Good luck with your project! Let me know if you have any questions.
Here's some code without the use of timers. Call startCountdown() every time you want to re-initialize the count-down. Call getAvailableScore() when you want to fetch the current available score. You will have to decide what to do when the available score goes to zero.
var beginCountDownTime;
function startCountdown() {
beginCountDownTime = new Date();
}
function getAvailableScore {
var now = new Date();
var delta = (now.getTime() - beginCountDownTime.getTime()) * 1000; // time elapsed in seconds
var points = 100 - (delta / 60);
return(Math.round(Math.max(points, 0))); // return integer result >= 0
}
Maybe something like:
// Ad score
var score = 0;
var pointsAvailable = 100;
//$('#score').text(score);
function foundMatchingBlocks(event, params) {
params.elements.remove();
score += pointsAvailable;
$('#score').text(score);
pointsAvailable = 100;
};
$(document).ready(function() {doTimer();});
function doTimer() {
setTimeout('reducePoints()',1000);
}
function reducePoints() {
if(pointsAvailable>40) {
pointsAvailable--;
}
doTimer();
}