jquery - Javascript setInterval/Timeout Not Working -
this question has answer here:
i'm trying timer type text, delete it, , repeat, cycling through array of header titles. can write once, limited understanding of timers hindering me. here's have far. before put write logic in it's own method, call writetext() plugin manually console, it's working once. here's link codepen
<!-- html --> <div class="holder"> <h1><span>lorem ipsum dolor sit amet, consectetur adipisicing </span><img id="cursor" src="https://copy.com/obelwqicr3fa"></h1> </div> // javascript // counter , array of text type in header var headerarray = [ "the internet can't teach marketing", "i wish learned in art school", "every successful startup does" ], headercounter = 0, // headercontainer = $('.holder h1 span'), headercontainer = document.queryselector('#cursor').previouselementsibling; // function type text function typetext(i) { $('.holder h1 span').text('').writetext(headerarray[i]); headercounter++; if (headercounter >= headerarray.length) { headercounter = 0; } } $(function() { // fades cursor in , out setinterval(function () { $('#cursor').fadetoggle(400); }, 400); // calls function type text setinterval(typetext(headercounter), 5000); }); // plugin writes out text typewriter (function($) { $.fn.writetext = function(content) { var contentarray = content.split(""), current = 0, elem = this; setinterval(function() { if(current < contentarray.length) { elem.text(elem.text() + contentarray[current++]); } }, 50); }; })(jquery); // plugin deletes text (function($) { $.fn.deletetext = function(content) { var newcontent = content.slice(0, content.length - 1), current = 0, elem = this; setinterval(function() { if (elem.text().length == 0) { elem.text(newcontent); current--; } }, 50); }; })(jquery);
here's working "fiddle" of code few edits: http://jsfiddle.net/p8tc9/
html:
<h1> <span id="header">asdf</span> <span id="cursor">|</span> </h1>
js:
// counter , array of text type in header var headerarray = [ "the internet can't teach marketing", "i wish learned in art school", "every successful startup does"], headercounter = 0; // plugin writes out text typewriter (function ($) { $.fn.writetext = function (content, finishedcallback) { var contentarray = content.split(""), current = 0, elem = this, intervalhandle; intervalhandle = setinterval(function () { if (current < contentarray.length) { elem.text(elem.text() + contentarray[current++]); } else { // dispose interval. clearinterval(intervalhandle); finishedcallback(); } }, 50); }; })(jquery); // fades cursor in , out setinterval(function () { $('#cursor').fadetoggle(400); }, 400); // function type text function typenext() { var text = headerarray[headercounter]; headercounter++; if (headercounter >= headerarray.length) { headercounter = 0; } $('#header').text('').writetext(text, waitthentypenext); } function waitthentypenext() { settimeout(typenext, 2000); } // things started. typenext();
Comments
Post a Comment