Jquery/Ajax/JavaScript Time Count Down Non-Stop - javascript

Can anyone give me Jquery function for Time Count Down , but work like this.
Time every 15 minutes (without stop).
When time is 0, do some Ajax update function and auto start again (Without click or refresh by myself)
The time like (TimeCountDown = TimeNow - (TimeNow+15minuts)).
I just can't find functions like this, and i don't know how to work with time.
Thanks for help.

var _TimerCount = 15;
var _Timer = setInterval(function(){
TimerCountDown();
},6000);
function TimerCountDown(){
if(_TimerCount !=0){
_TimerCount -=1;
}
else{
var currentdate = new Date();
var _DateString = currentdate.getDate() + " " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
_TimerCount = 15;
$.get("C# CODE FILE HERE eg. MyFile.ashx",{_DateTime:_DateString }).done(function(response){
//Your Response CODE HERE
alert(response);
});
}
}

I'm a little unclear on what you are trying to do.
I think you want something like this:
var timeOut = function() {
****Whatever you want the code to do every 15 minutes****
};
var main = function() {
setInterval(timeOut, 900000);
};
$(document).ready(main);
Note: time is in miliseconds so 1 second = 1000
JSFiddle: http://jsfiddle.net/kitsonbroadhurst/552nu/1/

Related

Showing multiple timer function in Angular.js

I am trying to display two timer on a webpage with different start times.
First timer only shows for 5 seconds and then after 10 seconds I need to show timer2.
I am very new to Angular and have put together following code.
It seems to be working fine except when the settimeout is called the third time it doesn't work correctly and it starts going very fast.
Controller
// initialise variables
$scope.tickInterval = 1000; //ms
var min ='';
var sec ='';
$scope.ti = 0;
$scope.startTimer1 = function() {
$scope.ti++;
min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
$scope.timer1 = min + ":" + sec;
mytimeout1 = $timeout($scope.startTimer1, $scope.tickInterval); // reset the timer
}
//start timer 1
$scope.startTimer1();
$scope.$watch('timer1',function(){
if($scope.timer1 !=undefined){
if($scope.timer1 =='00:05'){
$timeout.cancel(mytimeout1);
setInterval(function(){
$scope.startTimer2()
$scope.ti = 0;
},1000)
}
}
})
//start timer 2 after 2 mins and 20 seconds
$scope.startTimer2 = function() {
$scope.ti++;
min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
$scope.timer2 = min + ":" + sec;
mytimeout2 = $timeout($scope.startTimer2, $scope.tickInterval);
}
$scope.$watch('timer2',function(){
if($scope.timer2 !=undefined){
if($scope.timer2 =='00:05'){
$timeout.cancel(mytimeout2);
setInterval(function(){
$scope.startTimer1();
$scope.ti = 0;
},1000)
}
}
})
In my view I simply have
<p>{{timer1}}</p>
<p>{{timer2}}</p>
You're basically starting multiple startTimer function so it's adding up. If i understood your problem well you don't even need to have all those watchers and timeouts.
You just can use $interval this way :
$scope.Timer = $interval(function () {
++$scope.tickCount
if ($scope.tickCount <= 5) {
$scope.timer1++
} else {
$scope.timer2++
if ($scope.tickCount >= 10)
$scope.tickCount = 0;
}
}, 1000);
Working fiddle

Time Interval seconds run fast on tab changed Javascript

I have an issue that hold my neck with time interval. I am calculating my time/clock one second at a time with the function below.
Header.prototype= {
time_changed : function(time){
var that = this;
var clock_handle;
var clock = $('#gmtclock');
that.time_now = time;
var increase_time_by = function(interval) {
that.time_now += interval;
};
var update_time = function() {
clock.html(moment(that.time_now).utc().format("YYYY-MM-DD HH:mm") + " GMT");
};
update_time();
clearInterval(clock_handle);
clock_handle = setInterval(function() {
increase_time_by(1000);
update_time();
}, 1000);
},
};
The above works fine and increase my time a second at a time correctly . However. I added another event that fires on web changed or tab navigated.
var start_time;
var tabChanged = function() {
if(clock_started === true){
if (document.hidden || document.webkitHidden) {
start_time = moment().valueOf();
time_now = page.header.time_now;
}else {
var tnow = (time_now + (moment().valueOf() - start_time));
page.header.time_changed(tnow);
}
}
};
if (typeof document.webkitHidden !== 'undefined') {
if (document.addEventListener) {
document.addEventListener("webkitvisibilitychange", tabChanged);
}
}
The above fires when ever user leave the page and comes back . It add the delay to the time. However, i notice the second increase rapidly . and very past my timer does not fire very second any more as specified in the clock hand. It add second every milliseconds and fats. Please why this and how do i fix this ? My time run fast and ahead when ever i change tab and returned . Any help would be appreciated
Update
Below is my WS request function.
Header.prototype = {
start_clock_ws : function(){
var that = this;
function init(){
clock_started = true;
WS.send({ "time": 1,"passthrough":{"client_time" : moment().valueOf()}});
}
that.run = function(){
setInterval(init, 900000);
};
init();
that.run();
return;
},
time_counter : function(response){
var that = this;
var clock_handle;
var clock = $('#gmt-clock');
var start_timestamp = response.time;
var pass = response.echo_req.passthrough.client_time;
that.time_now = ((start_timestamp * 1000) + (moment().valueOf() - pass));
var increase_time = function() {
that.time_now += (moment().valueOf() - that.time_now);
};
var update_time = function() {
clock.html(moment(that.time_now).utc().format("YYYY-MM-DD HH:mm") + " GMT");
};
update_time();
clearInterval(clock_handle);
clock_handle = setInterval(function() {
increase_time();
update_time();
}, 500);
},
};
and in my WS open event
if(isReady()=== true){
if (clock_started === false) {
page.header.start_clock_ws();
}
}
In my WS onmessage event
if(type ==='time'){
page.header.time_counter(response);
}
Base on your suggestion, i modified my increase_time_by to
var increase_time_by = function() {
that.time_now += (moment().valueOf() - that.time_now);
};
It seems fine now. Would test further and see.
Instead of incrementing the clock by the value of the interval, just update the clock to the current time with each pass. Then it won't matter if you fire exactly 1000 ms apart or not.
You actually may want to run more frequently, such as every 500 ms, to give a smoother feel to the clock ticking.
Basically, it comes down to the precision of the timer functions, or lack thereof. Lots of questions on StackOverflow about that - such as this one.
Based on your comments, I believe you are trying to display a ticking clock of UTC time, based on a starting value coming from a web service. That would be something like this:
var time_from_ws = // ... however you want to retrieve it
var delta = moment().diff(time_from_ws); // the difference between server and client time
// define a function to update the clock
var update_time = function() {
clock.html(moment.utc().subtract(delta).format("YYYY-MM-DD HH:mm") + " GMT");
};
update_time(); // set it the first time
setInterval(update_time, 500); // get the clock ticking

only the last setInterval run

I have the following javascript code
function RefreshElastic() {
Elastic.refresh();
}
function ShowTime() {
var Sekarang = new Date();
var Waktu = Sekarang.getDate() + "/" +
Sekarang.getMonth() + " - " +
Sekarang.getHours() + ":" +
Sekarang.getMinutes();
$("#jam").html(Waktu);
Elastic.refresh();
}
var IntervalElastic = setInterval(function () {
RefreshElastic();
}, 500);
var IntervalTime = setInterval(function () {
ShowTime();
}, 1000 * 30);
I want to have 2 intervals, each has a function to call.
The RefreshElastic called only twice.
The ShowTime always called every 30 seconds.
Why is that?
Additional note:
I changed the millis for RefreshElastic to a larger value, like 5000. And RefreshElastic never called.

Countdown timer for use in several places at same page

I want to make a countdown timer, that can be used on several places in the same page - so I think it should be a function in some way.
I really want it to be made with jQuery, but I cant quite make it happen with my code. I have e.g. 10 products in a page, that I need to make a countdown timer - when the timer is at 0 I need it to hide the product.
My code is:
$(document).ready(function(){
$(".product").each(function(){
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
var elm = $(this).attr('id');
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
EDIT 1:
$(document).ready(function(){
$(".product").each(function(){
var elm = $(this).attr('id');
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
Do you have any solutions to this?
I'd probably use a single interval function that checks all the products. Something like this:
$(function() {
/* set when a product should expire.
hardcoded to 5 seconds from now for demonstration
but this could be different for each product. */
$('.product').each(function() {
$(this).data('expires', (new Date()).getTime() + 5000);
});
var countdown_id = setInterval(function() {
var now = (new Date()).getTime();
$('.product').each(function() {
var expires = $(this).data('expires');
if (expires) {
var seconds_remaining = Math.round((expires-now)/1000);
if (seconds_remaining > 0) {
$('.time-left', this).text(seconds_remaining);
}
else {
$(this).hide();
}
}
});
}, 1000);
});
You could also cancel the interval function when there is nothing left to expire.
Your problem seems to be that this doesn't refer to the current DOM element (from the each), but to window - from setTimeout.
Apart from that, you have an unnecessary domReady wrapper, forgot the # on your id selector, should use cached references and never rely on the timing of setInterval, which can be quite drifting. Use this:
$(document).ready(function(){
$(".product").each(function(){
var end = new Date(/* from something */),
toUpdate = $(".time_left", this);
prod = $(this);
countDown();
function countdown() {
var cur = new Date(),
left = end - cur;
if (left <= 0) {
prod.remove(); // or .hide() or whatever
return;
}
var sec = Math.ceil(left / 1000);
toUpdate.text(sec + " seconds remaining!"); // don't use .html()
setTimeout(countdown, left % 1000);
}
});
});

Running a real-time clock with AJAX

Now that I was helped getting AJAX running just great, I'm having problems running a clock function with it....
Clock code (located in the head):
<script type="text/javascript">
var ampm = "AM"; //Default
var message="";
function startTime()
{
var today = new Date(); //Number goes here
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
h=checkTime2(h);
document.getElementById('clocktxt').innerHTML=h+":"+m+":"+s+ " " +ampm + " " + message;
//t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
message = "How long you gonna sit there?";
}
return i;
}
function checkTime2(i)
{
if (i>12)
{
i=i-12;
ampm="PM";
}
return i;
}
//setInterval(startTime,1000);
</script>
AJAX code (bottom of the document):
<script type='text/javascript'>
function CheckForChange(){
//alert("<?echo (count($listArray)) . ' and ' . count(file($filename_noformat))?>");
//if (<?echo count($listArray)?> == <?echo count(explode("\n", $filename_noformat))?>){
//setInterval("alert('Yup, it is 1')", 5000);
//alert('Now it is changed');
//}
var ajaxReady = new XMLHttpRequest();
ajaxReady.onreadystatechange = function(){
if (ajaxReady.readyState == 4){
//Get the data
//document.getElementById('clocktxt').innerHTML = ajaxReady.responseText;
//startTime();
//alert("here");
//alert(ajaxReady.responseText);
}
}
ajaxReady.open("GET","ServerTime.php",true);
ajaxReady.send(null);
}
setInterval(CheckForChange(), 1000);
setInterval(startTime(),1000);
</script>
What I'm trying to do is pass the input from ServerTime.php which is just a count of milliseconds from Unix epoch, into the clock, so the clock is being updated by the AJAX every second and the clock function runs with a new starting value each second.... I used to have parameters for the clock function before I realized the clock wasn't even getting called.
What do you think is wrong? I'm guessing it has something to do with the clock and the caller of the clock being in two different script tags, but I can't think of how to get around it. For some reason when I moved the AJAX part into the same script tag, following the clock, nothing happens.
To Kolink: I have this
function getTheNow(){
TIMESTAMP = <?php echo time(); ?>000;
offset = new Date().getTime()-TIMESTAMP;
setInterval(function() {
var now = new Date();
now.setTime(now.getTime()-offset);
// print out the time according to the variable `now`
//alert(now);
},5000);
return now;
}
function startTime()
{
var now = getTheNow;
//alert(now);
var today = new Date(); //Number goes here
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
h=checkTime2(h);
document.getElementById('clocktxt').innerHTML=h+":"+m+":"+s+ " " +ampm + " " + message;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
message = "How long you gonna sit there?";
}
return i;
}
function checkTime2(i)
{
if (i>12)
{
i=i-12;
ampm="PM";
}
return i;
}
setInterval(startTime,1000);
Computer clocks are not so inaccurate that you have to re-sync them every second. Try every ten minutes, or even every hour.
In fact, I just do away with synchronising altogether. It is far easier to do this:
<script type="text/javascript">
TIMESTAMP = <?php echo time(); ?>000;
offset = new Date().getTime()-TIMESTAMP;
setInterval(function() {
var now = new Date();
now.setTime(now.getTime()-offset);
// print out the time according to the variable `now`
},1000);
</script>
JavaScript 101 error
setInterval(CheckForChange(), 1000);
setInterval(startTime(),1000);
You are not assigning the function, you are calling/executing them and saying what ever is returned from these functions should be set. Drop the () so you are referencing the functions.
setInterval(CheckForChange, 1000);
setInterval(startTime,1000);

Categories

Resources