Reputation: 135
I have a unix time eg: var later= 135000;
When I take the variable later -= 1000 I am able to get 134000.
But when I take the variable later += 1000 I get 1350001000.
How can I increase my unix time?
<script type="text/javascript">
var later = "<?php echo $unix_time; ?>";
var stop= setInterval('countdown()',1000);
function countdown(plus_ten) {
var now = new Date();
var now_time= now.getTime()/1000;
now_time= Math.floor(now_time);
if(plus_ten){
later = later + 1000;
alert(later);
}
var sec = later- now_time;
if(sec<=0){
clearInterval(stop);
alert('hello');
}
sec= Math.floor(sec);
var min = Math.floor(sec / 60);
var hour = Math.floor(min / 60);
hour %= 24;
min %= 60;
sec %= 60;
document.getElementById("hoursBox").innerHTML = hour;
document.getElementById("minsBox").innerHTML = min;
document.getElementById("secsBox").innerHTML = sec;
}
</script>
Upvotes: 2
Views: 153
Reputation: 46856
Remember that JavaScript is a loosely typed language. Whether your variable gets handled as a integer or a string depends on the context in which you use it.
The -
(minus) operator is obviously arithmetic, so JS knows to subtract. But the +
operator is also used to concatenate strings, so if you want JS to do addition, you may need to be more explicit. You've put the contents of later
inside double quotes, which hints to JS that you want it to be treated as a string. So:
var later = parseInt("<?php echo $unix_time; ?>");
or
later = later - 0 + 1000; /* hints at arithmetic, then adds 1000 */
Quotes are a Good Thing, in case $unix_time
contains something unexpected.
Upvotes: 3
Reputation: 66663
Your variable 'later' is assigned a string value when you do:
var later = "<?php echo $unix_time; ?>";
You should instead do:
var later = <?php echo $unix_time; ?>; // i.e. no quotes around the time stamp
That should fix it.
Upvotes: 2