简体   繁体   中英

Typewriter effect in a loop jquery - How to

I am trying to achieve a typewriter effect in jQuery and this is what I have achieved so far.

var text = 'Loading ...';

//text is split up to letters
$.each(text.split(''), function(i, letter){

    //we add 100*i ms delay to each letter 
    setTimeout(function(){

        //we add the letter to the container
        $('#container').html($('#container').html() + letter);

    }, 100*i);
});

This is give the effect one time, but I want it to run in a loop continuously.

I have set up a fiddle for what I have tried so far here

Thanks for looking

Just maintain a counter, and reset to 0 at the end of the string.

DEMO: http://jsfiddle.net/QPNTq/

var chars = 'Loading ...'.split('');
var container = document.getElementById("container");

var i = 0;
setInterval(function () {
    if (i < chars.length) {
        container.innerHTML += chars[i++];
    } else {
        i = 0;
        container.innerHTML = "";
    }
}, 100);

No need for .each() or any other kind of loop this way. Much simpler.

Wrap your code within a function (something named repeat ) and then call it using setInterval like

setInterval(function () {
    $('#container').html(''); //clear the container
    repeat();
}, 1100)

JSFiddle

JSFiddle

var text = 'Loading ...';

setInterval(function(){

$('#container').html("");

//text is split up to letters
    $.each(text.split(''), function(i, letter){

        //we add 100*i ms delay to each letter 
        setTimeout(function(){

            //we add the letter to the container
            $('#container').html($('#container').html() + letter);

        }, 100*i);
    });

}, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM