flaws in second's field increment in stop watch - javascript

<script>
var s=0;
var ms=0;
function timeDisp()
{
var d = new Date();
ms = d.getMilliseconds();
if(ms==999 && s<60)
{
s=s+1;
ms=0;
}
var r = (((s <10)?"0":":") + s + (":") + ms);
return r;
}
function display()
{
var t = timeDisp();
document.getElementById("time").value=t; //time is id of input text field
m=setTimeout('display()',1);
}
function stop()
{
clearTimeout(m);
}
</script>
I have written this code to create simple stop watch but there is flaw in increment in seconds field.Sometimes second do not increase as it should and sometime it skip one or two seconds while running.

Related

Can't use variable as setInterval delay? [duplicate]

I have written a javascript function that uses setInterval to manipulate a string every tenth of a second for a certain number of iterations.
function timer() {
var section = document.getElementById('txt').value;
var len = section.length;
var rands = new Array();
for (i=0; i<len; i++) {
rands.push(Math.floor(Math.random()*len));
};
var counter = 0
var interval = setInterval(function() {
var letters = section.split('');
for (j=0; j < len; j++) {
if (counter < rands[j]) {
letters[j] = Math.floor(Math.random()*9);
};
};
document.getElementById('txt').value = letters.join('');
counter++
if (counter > rands.max()) {
clearInterval(interval);
}
}, 100);
};
Instead of having the interval set at a specific number, I would like to update it every time it runs, based on a counter. So instead of:
var interval = setInterval(function() { ... }, 100);
It would be something like:
var interval = setInterval(function() { ... }, 10*counter);
Unfortunately, that did not work. It seemed like "10*counter" equals 0.
So, how can I adjust the interval every time the anonymous function runs?
You could use an anonymous function:
var counter = 10;
var myFunction = function(){
clearInterval(interval);
counter *= 10;
interval = setInterval(myFunction, counter);
}
var interval = setInterval(myFunction, counter);
UPDATE: As suggested by A. Wolff, use setTimeout to avoid the need for clearInterval.
var counter = 10;
var myFunction = function() {
counter *= 10;
setTimeout(myFunction, counter);
}
setTimeout(myFunction, counter);
Use setTimeout() instead. The callback would then be responsible for firing the next timeout, at which point you can increase or otherwise manipulate the timing.
EDIT
Here's a generic function you can use to apply a "decelerating" timeout for ANY function call.
function setDeceleratingTimeout(callback, factor, times)
{
var internalCallback = function(tick, counter) {
return function() {
if (--tick >= 0) {
window.setTimeout(internalCallback, ++counter * factor);
callback();
}
}
}(times, 0);
window.setTimeout(internalCallback, factor);
};
// console.log() requires firebug
setDeceleratingTimeout(function(){ console.log('hi'); }, 10, 10);
setDeceleratingTimeout(function(){ console.log('bye'); }, 100, 10);
I like this question - inspired a little timer object in me:
window.setVariableInterval = function(callbackFunc, timing) {
var variableInterval = {
interval: timing,
callback: callbackFunc,
stopped: false,
runLoop: function() {
if (variableInterval.stopped) return;
var result = variableInterval.callback.call(variableInterval);
if (typeof result == 'number')
{
if (result === 0) return;
variableInterval.interval = result;
}
variableInterval.loop();
},
stop: function() {
this.stopped = true;
window.clearTimeout(this.timeout);
},
start: function() {
this.stopped = false;
return this.loop();
},
loop: function() {
this.timeout = window.setTimeout(this.runLoop, this.interval);
return this;
}
};
return variableInterval.start();
};
Example use
var vi = setVariableInterval(function() {
// this is the variableInterval - so we can change/get the interval here:
var interval = this.interval;
// print it for the hell of it
console.log(interval);
// we can stop ourselves.
if (interval>4000) this.stop();
// we could return a new interval after doing something
return interval + 100;
}, 100);
// we can change the interval down here too
setTimeout(function() {
vi.interval = 3500;
}, 1000);
// or tell it to start back up in a minute
setTimeout(function() {
vi.interval = 100;
vi.start();
}, 60000);
I had the same question as the original poster, did this as a solution. Not sure how efficient this is ....
let interval = 5000; // initial condition
let run = setInterval(request, interval); // start setInterval as "run"
function request() {
console.log(interval); // firebug or chrome log
clearInterval(run); // stop the setInterval()
// dynamically change the run interval
if (interval > 200) {
interval = interval * .8;
} else {
interval = interval * 1.2;
}
run = setInterval(request, interval); // start the setInterval()
}
This is my way of doing this, i use setTimeout:
var timer = {
running: false,
iv: 5000,
timeout: false,
cb : function(){},
start : function(cb,iv){
var elm = this;
clearInterval(this.timeout);
this.running = true;
if(cb) this.cb = cb;
if(iv) this.iv = iv;
this.timeout = setTimeout(function(){elm.execute(elm)}, this.iv);
},
execute : function(e){
if(!e.running) return false;
e.cb();
e.start();
},
stop : function(){
this.running = false;
},
set_interval : function(iv){
clearInterval(this.timeout);
this.start(false, iv);
}
};
Usage:
timer.start(function(){
console.debug('go');
}, 2000);
timer.set_interval(500);
timer.stop();
A much simpler way would be to have an if statement in the refreshed function and a control to execute your command at regular time intervals . In the following example, I run an alert every 2 seconds and the interval (intrv) can be changed dynamically...
var i=1;
var intrv=2; // << control this variable
var refreshId = setInterval(function() {
if(!(i%intrv)) {
alert('run!');
}
i++;
}, 1000);
This can be initiated however you want. timeout is the method i used to keep it on the top of the hour.
I had the need for every hour to begin a code block on the hour. So this would start at server startup and run the interval hourly. Basicaly the initial run is to begin the interval within the same minute. So in a second from init, run immediately then on every 5 seconds.
var interval = 1000;
var timing =function(){
var timer = setInterval(function(){
console.log(interval);
if(interval == 1000){ /*interval you dont want anymore or increment/decrement */
interval = 3600000; /* Increment you do want for timer */
clearInterval(timer);
timing();
}
},interval);
}
timing();
Alternately if you wanted to just have something happen at start and then forever at a specific interval you could just call it at the same time as the setInterval. For example:
var this = function(){
//do
}
setInterval(function(){
this()
},3600000)
this()
Here we have this run the first time and then every hour.
I couldn't synchronize and change the speed my setIntervals too and I was about to post a question. But I think I've found a way. It should certainly be improved because I'm a beginner. So, I'd gladly read your comments/remarks about this.
<body onload="foo()">
<div id="count1">0</div>
<div id="count2">2nd counter is stopped</div>
<button onclick="speed0()">pause</button>
<button onclick="speedx(1)">normal speed</button>
<button onclick="speedx(2)">speed x2</button>
<button onclick="speedx(4)">speed x4</button>
<button onclick="startTimer2()">Start second timer</button>
</body>
<script>
var count1 = 0,
count2 = 0,
greenlight = new Boolean(0), //blocks 2nd counter
speed = 1000, //1second
countingSpeed;
function foo(){
countingSpeed = setInterval(function(){
counter1();
counter2();
},speed);
}
function counter1(){
count1++;
document.getElementById("count1").innerHTML=count1;
}
function counter2(){
if (greenlight != false) {
count2++;
document.getElementById("count2").innerHTML=count2;
}
}
function startTimer2(){
//while the button hasn't been clicked, greenlight boolean is false
//thus, the 2nd timer is blocked
greenlight = true;
counter2();
//counter2() is greenlighted
}
//these functions modify the speed of the counters
function speed0(){
clearInterval(countingSpeed);
}
function speedx(a){
clearInterval(countingSpeed);
speed=1000/a;
foo();
}
</script>
If you want the counters to begin to increase once the page is loaded, put counter1() and counter2() in foo() before countingSpeed is called. Otherwise, it takes speed milliseconds before execution.
EDIT : Shorter answer.
(function variableInterval() {
//whatever needs to be done
interval *= 2; //deal with your interval
setTimeout(variableInterval, interval);
//whatever needs to be done
})();
can't get any shorter
Here is yet another way to create a decelerating/accelerating interval timer. The interval gets multiplied by a factor until a total time is exceeded.
function setChangingInterval(callback, startInterval, factor, totalTime) {
let remainingTime = totalTime;
let interval = startInterval;
const internalTimer = () => {
remainingTime -= interval ;
interval *= factor;
if (remainingTime >= 0) {
setTimeout(internalTimer, interval);
callback();
}
};
internalTimer();
}
Make new function:
// set Time interval
$("3000,18000").Multitimeout();
jQuery.fn.extend({
Multitimeout: function () {
var res = this.selector.split(",");
$.each(res, function (index, val) { setTimeout(function () {
//...Call function
temp();
}, val); });
return true;
}
});
function temp()
{
alert();
}
This piece of code below accelerates (acceleration > 1) or decelerates (acceleration <1) a setInterval function :
function accelerate(yourfunction, timer, refresh, acceleration) {
var new_timer = timer / acceleration;
var refresh_init = refresh;//save this user defined value
if (refresh < new_timer ){//avoid reseting the interval before it has produced anything.
refresh = new_timer + 1 ;
};
var lastInter = setInterval(yourfunction, new_timer);
console.log("timer:", new_timer);
function stopLastInter() {
clearInterval(lastInter);
accelerate(yourfunction, new_timer, refresh_init, acceleration);
console.log("refresh:", refresh);
};
setTimeout(stopLastInter, refresh);
}
With :
timer: the setInterval initial value in ms (increasing or decreasing)
refresh: the time before a new value of timer is calculated. This is the step lenght
acceleration: the gap between the old and the next timer value. This is the step height
Inspired by the internal callback above, i made a function to fire a callback at fractions of minutes. If timeout is set to intervals like 6 000, 15 000, 30 000, 60 000 it will continuously adapt the intervals in sync to the exact transition to the next minute of your system clock.
//Interval timer to trigger on even minute intervals
function setIntervalSynced(callback, intervalMs) {
//Calculate time to next modulus timer event
var betterInterval = function () {
var d = new Date();
var millis = (d.getMinutes() * 60 + d.getSeconds()) * 1000 + d.getMilliseconds();
return intervalMs - millis % intervalMs;
};
//Internal callback
var internalCallback = function () {
return function () {
setTimeout(internalCallback, betterInterval());
callback();
}
}();
//Initial call to start internal callback
setTimeout(internalCallback, betterInterval());
};
This is my idea for times when you do not want loops like setInterval to overlap.
You also want to be able to set the loop execution delay and start and stop the loop, instansly on the fly.
I am using a loop_flag variable and a setTimeout function.
I set the main function to async so that you can call other functions in the body by calling await. When the main body of your code is running, the main loop waits and does not repeat itself. (which is not the case with setInterval)
An example of a simple code is:
//#NabiKAZ
document.getElementById("btn_start").addEventListener("click", function() {
console.log("Starting...");
loop_flag = true;
loop_func();
});
document.getElementById("btn_stop").addEventListener("click", function() {
console.log("Stoping...");
loop_flag = false;
});
var n = 0;
var loop_flag = false;
var loop_func = async function() {
if (!loop_flag) {
console.log("STOP.");
return;
}
//body main function inhere
n++;
console.log(n);
////
if (loop_flag) {
setTimeout(loop_func, document.getElementById("inp_delay").value);
} else {
console.log("STOP.");
}
}
<input id="inp_delay" value="1000">
<button id="btn_start">START</button>
<button id="btn_stop">STOP</button>
For a more complete code with a fetch request inside the loop, see here:
https://jsfiddle.net/NabiKAZ/a5hdw2bo/
You can use a variable and change the variable instead.
setInterval(() => function, variable)
You can do this by clearing the interval every iteration, changing the timer value and setting the interval again. Hope it helps ;)
For exemple:
const DOMCounter = document.querySelector(".counter")
let timer = 1000
const changeCounter = () => {
clearInterval(interval)
DOMCounter.innerHTML = timer
timer += 1000
timer == 5000 && timer == 1000
interval = setInterval(changeCounter, timer)
}
let interval = setInterval(changeCounter, timer)
<div class="container">
<p class="counter"></p>
</div>
var counter = 15;
var interval = function() {
setTimeout(function(){
// Write your code here and remove console.log, remember that you need declare yourDynamicValue and give it a value
console.log((new Date()).getTime())
window.counter = yourDynamicValue;
window.interval();
}, counter);
}
// It needs to run just once as init
interval();

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

Reduce setTimeout time relative to time left

I'm making a random "spinner" that loops through 8 divs and add a class active like this:
https://jsfiddle.net/9q1tf51g/
//create random setTimeout time from 3sec to 5sec
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var exit = false;
function repeat(){
//my code
if(!exit){
setTimeout(repeat, 50);
}
}
My problem is, I want the function repeat to end slowly, to create more suspense. I think I can do this by raising the 50 from the timeout but how can I do this accordingly to the time left?
Thanks in advance!
You can try this.
$('button').on('click', function(){
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var anCounter = 1;
var anState = "positive";
var exit = false;
//var time1 = 50000;
setInterval(function(){time = time-1000;}, 1000);
function repeat(){
if(anCounter>7 && anState=="positive"){ anState="negative"}
if(anCounter<2 && anState=="negative"){ anState="positive"}
$('div[data-id="'+anCounter+'"]').addClass('active');
$('div').not('div[data-id="'+anCounter+'"]').removeClass('active');
if(anState=="positive"){anCounter++;}else{anCounter--;}
if(!exit){
if(time <1000)
setTimeout(repeat, 300);
else if(time< 2000)
setTimeout(repeat, 100);
else setTimeout(repeat, 50);
}
}
repeat();
setTimeout(function(){
exit=true;
},time);
});
Once you know that you need to exit the flow (exit is true ) you can trigger some animation by creating a dorm linear serials of you code. Usually this animation should not last more than 2 sec.
You were kind of on the right track but it'd be easier to check the time you've passed by and increment accordingly at a fixed rate. I set it to increase by 50ms every iteration but you could change that to whatever you like.
Fiddle Demo
Javascript
$('button').on('click', function() {
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var anCounter = 1;
var anState = "positive";
var elapsed = 0;
var timer;
function repeat(timeAdded) {
if (anCounter > 7 && anState == "positive") {
anState = "negative"
}
if (anCounter < 2 && anState == "negative") {
anState = "positive"
}
$('div[data-id="' + anCounter + '"]').addClass('active');
$('div').not('div[data-id="' + anCounter + '"]').removeClass('active');
if (anState == "positive") {
anCounter++;
} else {
anCounter--;
}
if (elapsed < time) {
timer = setTimeout(function() {
repeat(timeAdded + 50);
}, timeAdded);
elapsed += timeAdded;
}
else {
clearTimeout(timer);
}
}
repeat(0);
});
You can add a parameter called intTime to your function repeat and inside that function you can adjust the next timeout and call the repeat function with the new timeout. each time it gets called it will take 20 ms longer. however you adjust the increment by changing the 20 in
var slowDown=20; to a different number.
var slowDown=20;
setTimeout ("repeat",50);
function repeat(intTime){
//my code
if(!exit){
intTime=Math.floor (intTime)+slowDown;
setTimeout(repeat(intTime), intTime);
}
}
And then you will need to create another timeout for the exit.
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var exit = false;
setTimeout ("stopSpinning",time);
function stopSpinning(){
exit = true;
}
so the whole thing should look something like this
var slowDown=20;
var time = Math.floor(Math.random() * (5000 - 3000 + 1)) + 3000;
var exit = false;
setTimeout ("stopSpinning",time);
setTimeout ("repeat",50);
function repeat(intTime){
//my code
if(!exit){
intTime=Math.floor (intTime)+20;
setTimeout(repeat(intTime), intTime);
}
}
function stopSpinning(){
exit = true;
}
Fiddle Demo
Linear deceleration: //values are just an example:
add a var slowDown = 0; inside the click event handler
add slowDown += 1; inside the repeat function
pass 50+slowDown to setTimeout
Curved deceleration:
add a var slowDown = 1;and a var curveIndex = 1.05 + Math.random() * (0.2); // [1.05-1.25)inside the click event handler
add slowDown *= curveIndex; inside the repeat function
pass 50+slowDown to setTimeout

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