更新2
倒是做這樣的事情(演示:http://plnkr.co/edit/QuaMV6x1vNB0kYPaU6i1?p=preview):
// The messages the user can currently see.
var messages = [];
// You have something like this in your code, presumably.
socket.on('new message', function(data) {
addChatMessage(data);
});
function addChatMessage(data) {
// First add the message to the dome, with a unique id for the timestamp text.
var messageElementId = 'chat-message-' + data.messageId;
$("#chat-list").prepend($("<div>" + data.message + "<i> (sent: <span id='" + messageElementId + "'>just now</span>)</i></div>"));
// When you no longer display that message in the DOM it from clear this array. I'd render the DOM based on this list if I were you.
messages.push({
messageElementId: messageElementId,
timestamp: data.timestamp
});
}
// By updating all the messages at once you don't have memory leaks.
setInterval(function() {
messages.forEach(function(message) {
var time = moment(message.timestamp).fromNow();
$("#" + message.messageElementId).text(time);
});
}, 1000);
更新1
鑑於這是你的代碼:
var newMsg= "<div id="chat-time">'+ moment().fromNow()+'</div>";
$("#chat-list").html(newMsg);
你可以這樣做,而不是:
var messageTimeStamp = new Date(); // You need to grab this from somewhere.
setInterval(function(){
var time = moment(messageTimeStamp).fromNow();
$("#chat-list").html(time);
}, 1000);
您需要使用moment(TIMESTAMP_OF_MESSAGE)
不moment()
做像這樣:
$(function(){
$("body").append($('<div id="chat-time"></div>'));
var messageTimeStamp = new Date();
var i = 0;
setInterval(function(){
var time = moment(messageTimeStamp).fromNow();
$("#chat-time").html('moment().from(messageTimeStamp): ' + time + '; setInterval calls made ' + i++);
}, 1000);
});
下面是演示。
http://plnkr.co/edit/QuaMV6x1vNB0kYPaU6i1?p=preview
該代碼沒有意義,請展示它的使用的完整上下文。 'setInterval()'爲每次使用返回一個唯一的標識符,所以它可以被取消。您的代碼永遠不會將'moment()'值返回給字符串 – charlietfl
@charlietfl,那麼我如何每秒更新一次該文本? –
@HiradRoshandel讓我知道如果我的答案不適合你。我也提供了一個演示。 –