There is such a task - to track the last message in the chat. I decided to track it in time, I collect an array, it only remains to pull out the very maximum value, since I'm still a beginner, I get confused in some things. This script displays -Infinity, and Google brings, although the question is, I understand that it is simple.

var timestamp = {}; $('a.times').each(function(i, el){ var val = $(el).attr('data-temp'); var name = $(el).attr('data-cgid'); timestamp[name] = Number(val); }); var maxTime = Math.max.apply(timestamp); console.log(maxTime); 
  • and how it collects from where - Sasuke
  • messages have the same container can take away all the elements with the class and choose the last one and this will remove what you need - Sasuke
  • type var T = document.getElementByClassName (class); var result = T [T.length - 1]. var text = result .innerHTML - Sasuke Nov.
  • The fact is that the chat itself was not written by me, I just got the task to make an alert, and the code is written so that every 5 seconds the chat is updated and the data from the database is displayed, if they have changed, then there should be an alert. That is why I am sampling in time to compare the values ​​and if the new is larger, then call the audio. Thank you for the answer) - Kirill Bulgakov

2 answers 2

First of all, as @ Sanitary said, it’s best to store chat messages in a data structure. As for your code, there are errors in it.

  1. Math.max.apply (null, numArray); works with an array, you declared and use timestamp as an object
  2. Accordingly, it is necessary to write data to this variable via push.
  3. Jquery has its own method for accessing the data attribute.

Here's how to recycle your code.

 var timestamp = []; $('a.times').each(function(i, el) { var val = $(el).data('temp'); var name = $(el).data('cgid'); timestamp.push(Number(val)); }); var maxTime = Math.max.apply(null, timestamp); console.log(maxTime); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="times" data-temp="123451" data-cgid="1"></a> <a class="times" data-temp="123452" data-cgid="2"></a> <a class="times" data-temp="123454" data-cgid="4"></a> <a class="times" data-temp="123453" data-cgid="3"></a> 

    I recommend using jQuery .last ()

    • it was necessary not the last but the maximum value - Kirill Bulgakov
    • @KirillBulgakov Well, as I understand it in a chat, messages are usually published sequentially in time and the lowest newest one (maximum time)? - Nsk