javascript - setInterval only runs once when trying to run a function that loops through querySelectorAll array -


i'm new javascript, may lack basic understanding, don't understand why there problem in code.

i'm trying create "console typing effect" means selected text should it's typed in "real time" after page loaded. know there similar effects out there, want in vanilla js (no frameworks).

what have done far (pseudo code):

  1. get elements .console-effect class end store them in "elementlist"
  2. loop through elements , add cursor @ end of text have.
  3. (here failed :() make cursor blink

while debugging found in after looping through cursors(to make them blink) once, method "elem.style.opacity" says element has "undefined"...

document.body.onload = function() {      function addcursor(element) {         // create span cursor character , give class of .cursor         var newspan = document.createelement('span'),             newspantext = document.createtextnode('|');         newspan.appendchild(newspantext);         newspan.classname = 'cursor';          //add newspan element var(passed trough function)         element.appendchild(newspan);     }      function animatecursor() {         var cursors = document.queryselectorall('.cursor');          (var = 0; < cursors.length; i++) {             cursors[i].style.opacity = '0';             settimeout(function() {                 cursors[i].style.opacity = '1';             }, 500 );         }     }      setinterval('animatecursor()', 1000);      var elementslist = document.queryselectorall('.console-effect');     (var = 0; < elementslist.length ; i++) {         addcursor(elementslist[i]);     }  }; 

your function called in timeout not know cursor:

settimeout(function() {   cursors[i].style.opacity = '1'; }, 500 ); 

something should work:

settimeout(function() {   this.style.opacity = '1'; }.bind(cursors[i]), 500 ); 

even if i'm sure find explainations, let me know if need help. btw: lambda ninja right passing function string- should change that


Comments