Inactive (and quick) way to remove top lines from text box

I have a web page that displays the last lines of 1000a log file, and then updates through AJAX every xsecond, loading new content (if any) and adding to textarea s $('#log').append(new_data), sort of tail -f.

Problems occur after some time, when too many lines are added and the page becomes slow or not responding.

Therefore, I would like to limit the number of lines to, say, 5000, so this means that I have to:

  • receive new_data
  • calculate overflow = 5000 - lines_ in_new_data - lines_in_textarea
  • if overflow > 0remove first overflowlines from textarea
  • add new_data to textarea

In my mind, this includes one or more split('\n')values textareaand new_data, and then use the lengths of the arrays and slicing, but I think if there is a more accurate or better way to accomplish this.

+3
source share
2 answers

You should be able to use one split, and then joinafter trimming the data, for example:

// on data retrieved
var total = ((textarea.value 
              ? textarea.value + "\n" 
              : "") 
          + new_data).split("\n");

if (total.length > 10) 
    total = total.slice(total.length - 10);

textarea.value = total.join("\n");

Working example: http://jsfiddle.net/ArvQ7/ (shortened to 10 lines for short)

+8
source

Something like this (perhaps a more useful demo link below):

HTML

<button id="clickme">More lines</button>
<br/>
<textarea id="log" rows="24" cols="80"></textarea>
<p>Lines: <span id="numLines">0</span></p>

Javascript

var $log = $('#log'),
    $button = $('#clickme'),
    $numLines = $('#numLines'),
    MAX_LINES = 5000,
    lorem_ipsum = ' Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    lineCounter = 0;

$button.click(function()
{
    $log.val($log.val() + generateMoreLines()).change();
});

$log.change(function ()
{
    var text = tail(MAX_LINES, $log.val());
    $log.val(text);
    $numLines.text(countNewlines(text));
});

function generateMoreLines()
{
    var buf = [];
    for (var i = 0; i < 1000; i++)
    {
        buf.push(lineCounter++ + lorem_ipsum);
    }
    return buf.join('\n');
}

function countNewlines(haystack)
{
    return count('\n', haystack);
}

function count(needle, haystack)
{
    var num = 0,
        len = haystack.length;
    for (var i=0; i < len; i++)
    {
        if (haystack.charAt(i) === needle)
        {
             num++;
        }
    }
    return num;
}

function tail(limit, haystack)
{
    var lines = countNewlines(haystack) + 1;
    if (lines > limit)
    {
        return haystack
            .split('\n')
            .slice(-limit)
            .join('\n');
    }
    return haystack;
}

Processing a new line is not perfect (do you consider all occurrences '\n'? What if the line starts or ends with '\n'?, Etc.).

: http://jsfiddle.net/mattball/3ghjm/

+3

All Articles