Kampee TonOi Kampee TonOi - 7 months ago 15
Ruby Question

How to count time on rails

<h1>TIME: <%= Time.now.strftime("%H:%M:%S") %></h1>

In the template, my time is stopped. I want to animate it time like a digital watch.

The time is changed when I refresh a page.

For example, I'm going to index page and now the time shows: 12:30:50 (HH:MM:SS). I refresh again and the time shows: 12:31:10.

I want to show my seconds like this: 50 51 52 53 54.....


function displayTime() {
    var timer=document.getElementById('timer');
    var currentdate = new Date(); 
    var hours = currentdate.getHours();
    var minutes = currentdate.getMinutes();
    var seconds = currentdate.getSeconds();
    timer.innerHTML = hours + ':' + minutes + ':' + seconds;    

setInterval(displayTime, 1000);
<h1>Time : 
    <p id="timer">
        <%= Time.now.strftime("%H:%M:%S") %>

First, let's create a function that displays the current date. For this, we just have to find the p tag we are interested in (using getElementById), and put use innerHTML to write in it. That's the function displayTime.

Then, we want to run this function every second, so we use : setInterval.

Note I keep <%= Time.now.strftime("%H:%M:%S") %> so that if javascript is not enabled there is still a date. If that's not the intended behavior then you can replace it.