Search code examples
javascripttimerclockzone

Bad refreshing in my clock zone


My English is very bad so I can do mistakes.

Two days ago I wrote clock zone but It is works badly. Look down You can see there my code. I need your advice.

<script>
        function Clock(time_zone) {
            var time    = new Date();
            var hours   = time.getUTCHours() + time_zone;
            var minutes = time.getUTCMinutes();
            var seconds = time.getUTCSeconds();
            var suffix  = "AM";
            var day = time.getDate();
            var month = time.getMonth();
            var year = time.getFullYear();
            var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");


            if (hours < 0) {
                hours += 24;
            }

            if (hours > 11) {
                suffix = "PM";
                hours -= 12;
            }

            if (hours == 0) {
                hours = 12;
            }

            if (hours < 10) {
                hours = "0" + hours;
            }

            if (minutes < 10) {
                minutes = "0" + minutes;
            }

            if (seconds < 10) {
                seconds = "0" + seconds;
            }

            var time_span = document.getElementById('time');
            var suffix_span = document.getElementById('suffix');
            var date_span = document.getElementById('date');
            time_span.innerHTML = hours + ":" + minutes + ":" + seconds;
            suffix_span.innerHTML = suffix;
            date_span.innerHTML = day + " " + months[month] + " " + year;

            setTimeout(function(){Clock(time_zone)}, 1000);
        }
        window.onload = function()
        {
            Clock(2);
        }
    </script>

Here is the button to change zone.

<input type="button" onClick="Clock(5)" value="AMSTERDAM" name="AMSTERDAM"/>

When i click this button my time blinks between old zone times(Clock(2)) and new zone times(Clock(5))

Could you tell me how to repair it???

Thanks for all advice.

Please, you will improve my language mistakes.


Solution

  • You need to cancel the original timeout

    if(window.timer) window.clearTimeout(window.timer);
    window.timer = setTimeout(function(){Clock(time_zone)}, 1000);