Change JavaScript interval time when current time is between two times - javascript

I’m looking for a way to tweak a current script of mine that loads a page into a div every minute. I want it to wait 5 minutes at a specific time, then go back to executing every minute. Here’s what I have so far.
var starttime = 10‎:‎30:‎00‎ ‎PM;
var endtime = 10‎:‎35:‎00‎ ‎PM;
var myVar = setInterval(function(){ myTimer() }, 1000);
function myTimer() {
var d = new Date();
document.getElementById("currenttime").innerHTML = d.toLocaleTimeString();
if ( d.toLocaleTimeString() > ‎starttime &&
d.toLocaleTimeString() < ‎endtime ) {
setInterval(function() {
}, 300000);
$("#ticketload").load("loadlasttenminutesmodified.php");
} else {
setInterval(function() {
}, 60000);
$("#ticketload").load("loadlasttenminutesmodified.php");
}
};
Any help is appreciated, thanks.

var starttime = '10‎:‎30:‎00‎ ‎PM',
endtime = '10‎:‎35:‎00‎ ‎PM';
var myVar = setInterval(myTimer, 1000);
// Use this function instead of toLocaleTimeString,
// since inconsistencies may arise with that one, depending on country.
function getTimeFormatted(date) {
var hours = date.getHours(),
minutes = date.getMinutes(),
seconds = date.getSeconds(),
ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
seconds = seconds < 10 ? '0' + seconds : seconds;
return hours + ':' + minutes + ':' + seconds + ' ' + ampm;
}
function myTimer() {
var d = getTimeFormatted(new Date());
document.getElementById("currenttime").innerHTML = d;
// Simply return (exit) the function when current time is
// between both of those dates.
// Your function will not go further than this.
// And it will effectively do nothing other than update the innerHTML
// for about five minutes.
if (d > ‎starttime && d < ‎endtime) return;
// Do the stuff that is supposed to run every minute.
// I assume this is, but place whatever else you want in here.
$("#ticketload").load("loadlasttenminutesmodified.php");
}
You can just exit out of the interval with return when the time criteria is met, before executing the rest of the code that is supposed to run every minute.
I made some changes to your code:
You missed quotes in your starttime and endtime variables
Replaced toLocaleTimeString with a new function. Thanks to #SpiderPig for pointing out why toLocaleTimeString isn't reliable.
You can specify the function directly in the myVar interval, instead of executing the myTimer function inside of an anonymous function.
Format the current day into AM/PM once, since that's all that is needed.
return when the time criteria is met and before executing the rest of the code inside of the interval.
I don't know what those empty setIntervals were in there for, so I removed them. I guess this is just example code, judging from the variable names you gave.

Try
var startTime = "22:30:00",
endTime = "22:35:00",
currentTime = $("#currenttime"),
ticketLoad = $("#ticketload"),
delay = 60000,
extendedDelay = delay * 5,
timeout = null,
timer = function timer(delay) {
var cycle = function cycle(delay, reset) {
// clear `queue` if within `startTime` , `endTime` range,
// `reset` set to `true`
if (reset) {
this.queue("timer", []);
};
// `cycle` delay `60000`
this.html("currenttime called at:" + new Date().toLocaleString())
// set `cycle` delay to `300000`
// if within `startTime` , `endTime` range,
// `reset` set to `true`
var _delay = !reset ? delay : extendedDelay;
.delay(_delay, "timer")
.queue("timer", function() {
console.log(new Date().toLocaleString());
// continue cycle
timer.call($(this), _delay);
}).dequeue("timer");
// do ajax stuff
ticketLoad.load("loadlasttenminutesmodified.php")
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(errorThrown);
// clear `queue` on `error`
currentTime.queue("timer", [])
});
};
// if within `startTime` , `endTime` range
// clear `queue` , set `cycle` delay to `300000`
if (String(new Date()).split(" ")[4] > startTime
&& String(new Date()).split(" ")[4] < endTime) {
cycle.call(this, delay, true);
timeout = setInterval(function() {
if (String(new Date()).split(" ")[4] >= endTime) {
clearInterval(timeout);
timeout = null;
this.queue("timer", []);
cycle.call(this, delay)
}
}.bind(this), 7500)
} else {
if (String(new Date()).split(" ")[4] >= endTime) {
this.queue("timer", []);
cycle.call($(this), delay)
} else {
cycle.call($(this), delay)
}
};
};
timer.call(currentTime, delay);
$(function() {
var startTime = "22:30:00",
endTime = "22:35:00",
currentTime = $("#currenttime"),
ticketLoad = $("#ticketload"),
delay = 60000,
extendedDelay = delay * 5,
timeout = null,
timer = function timer(delay, reset) {
var cycle = function cycle(delay, reset) {
if (reset) {
this.queue("timer", [])
};
var _delay = !reset ? delay : extendedDelay;
this.html("currenttime called at:" + new Date().toLocaleString())
.delay(_delay, "timer")
.queue("timer", function() {
console.log(new Date().toLocaleString());
timer.call($(this), _delay)
}).dequeue("timer");
$.when(ticketLoad)
.always(function(data) {
this.html("ticketLoad called at:" + new Date().toLocaleString())
})
};
if (String(new Date()).split(" ")[4] > startTime
&& String(new Date()).split(" ")[4] < endTime) {
cycle.call(this, delay, true);
timeout = setInterval(function() {
if (String(new Date()).split(" ")[4] >= endTime) {
clearInterval(timeout);
timeout = null;
this.queue("timer", []);
cycle.call(this, delay)
}
// check if beyond `endTime` ,
// reset `cycle`
// adjust interval duration here
// for greater, less frequency of checks
}.bind(this), 7500)
} else {
if (String(new Date()).split(" ")[4] >= endTime) {
this.queue("timer", []);
cycle.call($(this), delay)
} else {
cycle.call($(this), delay)
}
};
};
timer.call(currentTime, delay)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="currenttime"></div>
<div id="ticketload"></div>

Date.prototype.setMyTime = function (time) {
arrTime = time.split(":");
this.setHours(arrTime[0],arrTime[1],arrTime[2]);
return this;
}
var d = new Date();
var starttime = d.setMyTime('22:30:00');
var endtime = d.setMyTime('22:35:00');
var intervalId, loading = false;
var myVar = setInterval(function(){ myTimer() }, 1000);
function myTimer() {
var d = new Date();
document.getElementById("currenttime").innerHTML = d.toLocaleTimeString();
if(d.getTime() > starttime.getTime() && d.getTime() < endtime.getTime()) {
clearInterval(intervalId);
loading = false;
} else {
if (loading === false) {
intervalId = setInterval(function(){ $("#ticketload").load("loadlasttenminutesmodified.php"); }, 60000);
loading = true;
}
}
}

I decided to take a different approach. Set the interval to one minute and have and if statement inside that. Also, I needed to convert the time format into the same format as my variables.
<script type="text/javascript">
starttime = '10:30:00 PM';
endtime = '10:35:00 PM';
var myVar = setInterval(function(){ myTimer() }, 60000);
function myTimer() {
var timenow = new Date();
timeconvert = timenow.toLocaleTimeString()
if (timeconvert > starttime && timeconvert < endtime)
{
//alert("Time is 5 minutes");
}
else
{
//alert("Time is 60 seconds");
$("#ticketload").load("loadlasttenminutesmodified.php");
}
};
</script>
This has been working great all week.

Related

Start javascript stopwatch from a specific dynamic value

Before asking the question I would like to inform you that I've already searched in the questions with related topics , but my issues are different from others. Actually, I am building a "Javascript stopwatch", but there are some issues in the script that I've tried and searched to solve but can't find none. There are there issues in the stopwatch:
The stopwatch restarts automatically when page reloads even though the timer was stopped by the "stop_btn".
The stopwatch restarts automatically with the time comparing starting time and present time when page reloads; the paused time is totally ignored !
Can the stopwatch be started from a specific dynamic value; something like PHP variable as:
$time = "01:06:39"; ?
The Javascript:
var timer;
var startTime;
var isRunning = false;
var waitedTime = 0;
var stoppedTime = 0;
function start() {
if (isRunning) return;
isRunning = true;
startTime = parseInt(localStorage.getItem('startTime') || Date.now());
if (timer) {
waitedTime += (Date.now() - stoppedTime);
}
localStorage.setItem('startTime', startTime);
timer = setInterval(clockTick, 100);
}
function stop() {
isRunning = false;
clearInterval(timer);
stoppedTime = Date.now();
}
function reset() {
isRunning = false;
stoppedTime = 0;
waitedTime = 0;
clearInterval(timer);
timer = undefined;
localStorage.removeItem('startTime');
document.getElementById('display-area').innerHTML = "00:00:00.000";
}
function clockTick() {
var currentTime = Date.now(),
timeElapsed = new Date(currentTime - startTime - waitedTime),
hours = timeElapsed.getUTCHours(),
mins = timeElapsed.getUTCMinutes(),
secs = timeElapsed.getUTCSeconds(),
ms = timeElapsed.getUTCMilliseconds(),
display = document.getElementById("display-area");
display.innerHTML =
(hours > 9 ? hours : "0" + hours) + ":" +
(mins > 9 ? mins : "0" + mins) + ":" +
(secs > 9 ? secs : "0" + secs) + "." +
(ms > 99 ? ms : ms > 9 ? "0" + ms : "00" + ms);
};
var stopBtn = document.getElementById('stop_btn');
var startBtn = document.getElementById('start_btn');
var resetBtn = document.getElementById('reset_btn');
stopBtn.addEventListener('click', function() {
stop();
});
startBtn.addEventListener('click', function() {
start();
});
resetBtn.addEventListener('click', function() {
reset();
})
start();
Can anyone help please ?
You can add this new variable and then use it in the start function. If the custom time is defined then localstorage or current date will be ignored.
var customStartTime = new Date() // enter your custom date in the Date() function.
Then modify the starttime in the start() function
startTime = customStartTime || parseInt(localStorage.getItem('startTime') || Date.now());
Have you considered using window.onload handler from which you can load stopwatch value after page reload, I think this should cover first 2 issues you mentioned.
Also when you reload page stoppedTime variable will be 0, use localStorage to cache stoppedTime.

Timer does not want to stop by .prototype.stop

Why timer clock.start(); does not want to stop by using function clock.stop();.
I'm using typical function clearInterval in prototype stop to stop function start. Bur after calling clock.stop(); the timer in function clock.start(); does not stop.
I can not understand why...
function Clock(options) {
this._template = options.template;
}
Clock.prototype._render = function() {
var date = new Date();
var hours = date.getHours();
if (hours < 10) hours = '0' + hours;
var min = date.getMinutes();
if (min < 10) min = '0' + min;
var sec = date.getSeconds();
if (sec < 10) sec = '0' + sec;
var output = this._template.replace('h', hours).replace('m', min).replace('s', sec);
console.log(output);
};
Clock.prototype.start = function() {
this._render();
var self = this;
this._timer = setInterval(function() {
self._render();
}, 1000);
};
Clock.prototype.stop = function() {
setTimeout(function() {
clearInterval(this._timer);
console.log('Stop!'); // message is displayed, but timer in **this._timer** does not stop...
}, 5000);
};
var clock = new Clock({
template: 'h:m:s'
});
clock.start();
clock.stop();
To solve a problem in a function clock.stop();, it is necessary to apply a closure similarly applied to the function clock.start();
So we need to put the this._timer in the local variable and accessing directly to they by using the clouser method.
in the Clock.prototype.start we did clouser
this._render();
var self = this;
So we need to make the same in Clock.prototype.stop such
var sef = this._timer;
and use local variable sef in the timer function.
So simple, but I understand it only now.
Thanks to #elclanrs for a aiming :)

Javascript script timer issue

I am trying to make a count down timer. I manage to make one but the problem with this is it stops when I close browser. So when user revisit my site it restart again. What I want is to keep that timer. For example, if user leaves my site at timer 22:14:09. So timer will continue. Lets say the user revisits my site after an hour so the time should be 21:14:09. How can I do that?
Here is my JS
$(function () {
var hrs, mins, secs, TimerRunning, TimerID,
Timer = {
init: function () {
hrs = 23;
mins = 59;
secs = 59;
TimerRunning = false;
Timer.StopTimer();
Timer.StartTimer();
},
StopTimer: function () {
if(TimerRunning)
clearTimeout(TimerID);
TimerRunning=false;
},
StartTimer: function () {
TimerRunning = true;
$('.timer').html(Timer.Pad(hrs) + ":" + Timer.Pad(mins) + ":" + Timer.Pad(secs));
TimerID = self.setInterval("StartTimer()", 1000);
if(hrs == 0 && mins == 0 && secs == 0)
StopTimer();
if (secs == 0) {
mins--;
secs = 59;
}
if (mins == 0) {
hrs--;
mins = 59;
}
secs--;
setTimeout(function () { Timer.StartTimer(); }, 1000);
},
Pad: function (number) {
if(number < 10)
number = 0+""+number;
return number;
}
};
Timer.init();
});
Update
DEMO
Here is my solution for this problem.
// use hours, minutes & seconds to set time limit
var hours = 1,
minutes = 30,
seconds = 0,
maxTime = ( ( hours * 3600 ) + ( minutes * 60 ) + seconds ) * 1000,
// if timeleft not in localStorage then default to maxTime
timeLeft = ( localStorage.timeLeft || maxTime ),
startTime = new Date(),
intervalRef;
// check if user has already used up time
if( timeLeft > 0 ) {
intervalRef = setInterval( setTimeLeft, 5000 );
} else {
stopTrackingTime();
}
function setTimeLeft( ) {
// if user has used up time exit
if( localStorage.timeLeft < 0 ) {
stopTrackingTime();
}
// calculate how long user has left
var elapsed = ( new Date() - startTime );
localStorage.timeLeft = timeLeft - elapsed;
};
// function called once user has used up time
function stopTrackingTime( ) {
clearInterval( intervalRef );
alert( "end of time allowed" );
}
Fiddle here
You could store the time in LocalStorage, and it would be persistent across browser restarts.
In your case something as simple as
localStorage["mytimer"] = JSON.stringify([hrs, mins, secs]);
should work for storage, and you could do
var previousTime = JSON.parse(localStorage["mytimer"]);
to retrieve the previous value.
You could read more about it here: http://diveintohtml5.info/storage.html.
You could modify your StartTimer function so that every time it is called a local time stamp (new Date) be saved in cookie or localStorage. Besides, the setTimeout isn't very reliable, your should adjust the time count with real time every now and then.

Recurrent Javascript countdown

I have an annoying problem, i have trying to implement a simple 10 or 15 minute recurrent countdown. i have tried jQuery but it just gives me options to count down to a date and stops after the countdown is finished.
I found the below code Here but i cant figure it to remove the days and make it to count down for 10 or 15 minuters. Can someone please help me?
<div id="countre3">Loading...</div>
<script type="text/javascript">
function mycountre(o, timeArray){
var countre = document.getElementById(o);
if(!countre) {
return;
}
// helper functions
function mksec(day, h, m, s){ return day*24*60*60+h*60*60+m*60+s; }
function toTimeString(sec, showZero){
var d=Math.floor(sec/(60*60*24))
var h=Math.floor(sec/(60*60)%24);
var m=Math.floor((sec/60) % 60);
var s=sec % 60;
var ret=d+'days '+h+'hrs '+m+'min '+s+'sec';
if(showZero){
return ret;
}else if(d==0 && h==0 && m==0){
return s+'sec';
}else if(d==0){
return h+'hrs '+m+'min '+s+'sec';
}else if(d==0 && h==0){
return m+'min '+s+'sec';
}else {
return ret;
}
}
//
var secArray = [];
var dayNow = new Date().getDay();
for(var i=0;i<timeArray.length;i++){
var day=timeArray[i][0];
if(day==-1){
day=dayNow;
}
secArray.push({
day: timeArray[i][0],
sec: mksec(day, timeArray[i][2], timeArray[i][2], timeArray[i][3]),
msg: timeArray[i][4] || false,
showZero: timeArray[i][5] || false
});
}
secArray.sort(function(a,b){ return a.sec-b.sec;});
// timer code - will be called around each second (~1000 ms)
function updatecountre(){
// get current UTC time in seconds
var d=new Date();
var secNow = mksec(d.getDay(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds());
// find next event
var nextIndex=0;
for(var i=0;i<secArray.length; i++){
var diff = secArray[i].sec-secNow;
if(diff>0){
nextIndex=i;
break;
}
}
//
var diff=secArray[nextIndex].sec-secNow;
var prevDiff=diff;
if(diff<0){
var dayDiff = 6-secArray[nextIndex].day;
if(secArray[nextIndex].day == -1){
dayDiff=0;
}
diff=(dayDiff+1)*24*60*60-Math.abs(diff);
}
var str='';
// get message if there is any set
if(secArray[nextIndex].msg){
str=secArray[nextIndex].msg;
}
var timeString = toTimeString(diff, secArray[nextIndex].showZero);
if(str.match('#{countre}')!=null){
str=str.replace(/#{countre}/, timeString);
}else if(str.indexOf(' ')==0){ // message starts with space
str=timeString+str;
}else{ // no specific hint where to put countre, so display it after message
str+=timeString;
}
countre.innerHTML=str;
}
setInterval(updatecountre, 1000);
};
mycountre('countre3', [ [5, 5, 0, 0, '<center><b>Next Turns are Due in </b><p class="smalltext"> #{countre}</center>', false] ]);
</script>
Try this:
function mycountre(countdownId, countdownSeconds, countdownLooping){
var countre = document.getElementById(countdownId); // get html element
if (!countre) {
return;
}
var target = new Date().getTime() + 1000 * countdownSeconds; // target time
var intervalId; // id of the interval
// update function
function updatecountre(){
var time = Math.floor((target - new Date().getTime()) / 1000); // countdown time in seconds
if (time < 0) { // if countdown ends
if (countdownLooping) { // if it should loop
target += 1000 * countdownSeconds; // set new target time
time = Math.floor((target - new Date().getTime()) / 1000); // recalculate current time
} else { // otherwise
clearInterval(intervalId); // clear interval
time = 0; // set time to 0 to avoid displaying negative values
}
}
// split time to seconds, minutes and hours
var seconds = '0' + (time % 60);
time = (time - seconds) / 60;
var minutes = '0' + (time % 60);
time = (time - minutes) / 60;
var hours = '0' + time;
// make string from splited values
var str = hours.substring(hours.length - 2) + ':' + minutes.substring(minutes.length - 2) + ':' + seconds.substring(seconds.length - 2);
countre.innerHTML = str;
}
intervalId = setInterval(updatecountre, 200); // start interval to execute update function periodically
};
mycountre(
'countre3', // id of the html element
15 * 60, // time in seconds (15min here)
true // loop after countdown ends?
);
Working demo: http://jsfiddle.net/Xv3jx/1/
Small attempt for a jQuery plugin - more generic without minute/hour calc to avoid that the exaple gets too big:
(function($) {
$.fn.countdown = function(params) {
this.each(function() {
container = $.extend({
t: $(this),
stepSize: 1000, // milliseconds
duration: 3600, // seconds
offset: 0,
stepCallback: function() {},
finishCallback: function() {},
interval: function() {
if (this.offset>this.duration) {
this.finishCallback();
} else {
this.stepCallback();
}
this.offset += this.stepSize/1000;
}
}, params);
setInterval(function() {
container.interval();
}, container.stepSize);
});
return this;
};
})(jQuery);
Can be used with:
$('.main').countdown({
stepCallback: function() { console.log('step');},
finishCallback: function() { console.log('done');}
});
A simple countdown would then be implemented like this:
$('.main').countdown({
duration: 300,
stepCallback: function() {
var time = this.duration-this.offset
var seconds = '0' + (time % 60);
time = (time - seconds) / 60;
var minutes = '0' + (time % 60);
time = (time - minutes) / 60;
var hours = '0' + time;
var str = hours.substring(hours.length - 2) + ':' + minutes.substring(minutes.length - 2) + ':' + seconds.substring(seconds.length - 2);
$(this.t).html(str);
},
finishCallback: function() { $(this.t).html('tadaaa'); }
});
Cheers

Javascript reset countdown

Hello
I have a problem with countdown by javascript, i wrote a script and not bad.
i need reload countdown after few minute by ajax (json) but after loading new data script does not work properly.
after obtaining a new time counting time pours or not display!
help me pleas
thanks :)
var d = today();
function today(){
now = new Date().getTime();
return Math.round(now/1000);
}
function countdown(time1,id)
{
off = today() - d;
time = time1 - off;
h = Math.floor(time / 3600);
m = Math.floor(time / 60) % 60;
s = time % 60;
t = h + ":";
if(m < 10){ t += "0"; }
t += m + ":";
if (s < 10) { t += "0"; }
t += s;
//done
if(m <= 0 && s <= 0){
$("#"+id).html("00:00:00");
return;
}
$("#"+id).html(t).show();
var sto = window.setTimeout("countdown('"+time1+"','"+id+"')", 1000);
}
$(document).ready(function(){
//clearTimeout(sto);
countdown(1000, 'timer1');
countdown(1200, 'timer2');
//example (instead of json)
setTimeout(function(){
countdown(3000, 'timer1');
countdown(3200, 'timer2');
//alert('after click ok scripts is worked!');
}, 3000)
});
You can reset a timeout by doing window.clearTimeout(sto).
James Khoury suggests removing the var keyword from sto after declaring var sto; in the global namespace.
Below I summarize how to do these kinds of timing things in javascript:
Let's begin with some date and time manipulation functions:
// Time functions
// default unit is the millisecond
var sec = 1000;
var ms = 1;
function formatSeconds(time) {
var seconds = Math.floor(time/1000);
with (Math) {
var sec = seconds % 60;
var min = floor(seconds/60) % 60;
var hr = floor(seconds/3600);
}
return hr+':'+min+':'+sec;
}
function now() {
return (new Date()).getTime();
}
Now the actual interesting code:
// Timeout functions
function callPeriodically(params) {
/*
* PARAMS: {callback=function, callbackInterval=int, cleanupCallback=function}
*
* WHAT THIS FUNCTION DOES:
* Calls [[callback()]] every [[callbackInterval]] milliseconds;
* (The [[callback()]] function should return false if it wishes
* to abort callbacks.)
*
* RETURN VALUE: a function which, when called, will abort the periodic callbacks.
*
* Nomatter how periodic callbacks are aborted, the [[cleanupCallback()]] function
* is always run last thing.
*/
var callback = params['callback'];
var callbackInterval = params['callbackInterval'];
var cleanupCallback = params['cleanup'];
var timeout = window.setTimeout(makeClock());
var timer = function() {
if (callback()) # stop if callback() returns false
timeout = window.setTimeout(timer, callbackInterval);
else if (cleanupCallback)
cleanupCallback();
};
var cancel = function() {
window.clearTimeout(timeout);
cleanupCallback();
}
return cancel;
}
Making a clock callback which uses the above machinery:
function makeClockCallback(duration, htmlId) {
// enclose endTime in a closure:
var startTime = now();
var endTime = startTime + duration;
var countdown = function() {
var timeLeft = endTime - now();
$('#'+htmlId).html(formatSeconds(timeLeft));
return timeLeft>0; # continue as long as timeLeft>0
};
return countdown;
}
Now let's test it:
// Demo
function makeAndRunClock(htmlId) {
return callPeriodically({
callback = makeClockCallback(1000*sec, htmlId),
callbackInterval = 1000*ms,
cleanupCallback = function() {
alert(htmlId+' has been cancelled!');
}
);
}
var abortClock1 = makeAndRunClock(7*sec); // will naturally stop after 7sec
var abortClock2 = makeAndRunClock(10*sec); // will naturally stop after 10sec
window.setTimeout(
function() {
abortClock1(); // force clock1 to stop after 4sec
},
4*sec
);
There are a few syntax errors, but there you go.

Categories

Resources