Coffeescript:使用coffeescript动态更新时间 [英] Coffeescript: Dynamically update time with moment js with coffeescript

查看:239
本文介绍了Coffeescript:使用coffeescript动态更新时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法动态查看时刻js的时间更新。它显示正确的时间,但我必须刷新我的浏览器,以获得时间更新。我想它实时更新。像momentjs.com主页。

I am having trouble dynamically seeing the time update with moment js. It shows the correct time but I have to refresh my browser to get the time update. I would like it to update it in real time. Like momentjs.com main page.

我试过使用setInterval和setTimeout,但由于某种原因,我得到下面的数字,甚至不更新。

I've tried using setInterval and setTimeout but for some reason I get the below digits that don't even update.

这里是我到目前为止的代码。很简单,只要时刻和我想要的是秒,以继续计数...

Here's what I have so far code-wise. Pretty simple as far as moment goes and all I want is seconds to keep counting...

update = ->
  time = moment().format('hh:mm:ss a')

clock = setInterval update, 1000
console.log(clock) //output: 53296

任何想法都非常赞赏。

Any ideas are immensely appreciated.

推荐答案

你应该把输出放在update方法里面,一切都会正常工作。
方法setInterval不会返回重复调用方法的结果,而是一个可以与clearInterval结合使用以停止执行的标识符。

You should put the output inside of the update method and everthing will work as expected. The method setInterval won't return the result of the repeatedly called method but an identifier which can be used with clearInterval to stop the execution.

只是一个小工作示例每秒打印时间并在10秒后停止:

Just a small working example to print the time every seconds and stop after 10 seconds:

update = ->
    console.log(moment().format('hh:mm:ss a'))
x = setInterval update, 1000;
setTimeout (-> clearInterval(x)), 10000

作为一些DOM元素的内容,你可以使用下面的代码在你的更新函数(假设你有一个元素(例如div)id为time):

If you want to use that time as content of some DOM-Element you can use the following code inside your update function (assuming you have an element (e.g. div) with id "time"):

::

JQuery:

$("#time").text(moment().format('hh:mm:ss a')) 

Plain JS: / p>

Plain JS:

document.getElementById("time").firstChild.data = moment().format('hh:mm:ss a')

这篇关于Coffeescript:使用coffeescript动态更新时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆