Simulate scrolling text in javascript

前端 未结 5 1424
清酒与你
清酒与你 2021-01-16 20:52

I\'m trying to come up with something to simulate an old school modem connection. I.E. text that paints itself at variable speeds rather than rendering at once.

Her

5条回答
  •  孤街浪徒
    2021-01-16 21:13

    This seems a little bit faster, at least in FireFox. Despite the complete rewrite, the only real difference is not using jQuery or the string length property inside the "loop". I also added the ability to do more than one character at a time. 5-10 character seems a good range.

    function TextTyper(targetElement, charsAtATime, textToType) {
        var i,
            l = textToType.length,
            timeout,
            el = $(targetElement)[0],
            textNode = el.childNodes[0];
        if (!textNode) {
            textNode = document.createTextNode('');
            el.appendChild(textNode);
        }
        this.begin = function() {
            i = 0;
            if (timeout) { clearTimeout(timeout); }
            textNode.nodeValue = '';
            typeChar();
        };
        console.log(textNode);
        function typeChar() {
            if (i < l) {
                textNode.nodeValue += textToType.substr(i, charsAtATime);
                i += charsAtATime;
                timeout = setTimeout(typeChar, 1);
            } else {
                timeout = 0;
            }
        }
    }
    
    (new TextTyper('#test', 8, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam rhoncus urna vitae mi aliquet suscipit. Nullam vulputate ultrices tortor vel luctus. Duis sodales lacinia consequat. Vestibulum vehicula, ligula sit amet tincidunt scelerisque, orci arcu malesuada odio, eu ornare ipsum risus at metus. Nullam porttitor condimentum nunc, nec euismod massa consectetur id. Mauris ut nisl nulla, et tristique sem. In non ante vel libero lacinia vehicula in quis urna. Suspendisse urna erat, ornare sit amet rhoncus eget, bibendum at ipsum.'))
       .begin();
    

    I observed some best practices with closures and scope here. But you should get rid of your TextTyper objects on page unload, and should dispose of them properly without creating new ones in tight loops (or you can leak memory with the closure on targetElement).

    See this in action at jsfiddle.

    Note: I chose setTimeout instead of setInterval because I didn't want multiple invocations of the same script to step on each other. Given the speed the code runs, I doubt that it could, but it's good design practice. If this were an Ajax call, you wouldn't want to saturate the server with requests before the answer from the first request had come.

提交回复
热议问题