0

I want to find elements with javascript with delay. In first step I made this and it works.

function mytag() {
  var elements = document.getElementsByTagName('div');

  for (var i=0, im=elements.length; im>i; i++) {
    if (elements[i].className ==='hi'){

        alert('found');

    }}
  }

In the second step, I made some changes to code to put delay between iteration. I followed this link but cannot make it to work . Whats wrong?

function mytag() {
  var elements = document.getElementsByTagName('div'); 

  for (var i=0, im=elements.length; im>i; i++) {
   (function(i){
      setTimeout(function(){
        if (elements[i].className ==='hi'){
          alert('found!');
        }
      }, 3000 * i);
    }(i));
  }
}
Community
  • 1
  • 1
David Peterson
  • 552
  • 14
  • 31

2 Answers2

2

Here's an example of how you could add asynchronousity into your lookup function:

function findElements() {
  var elements = document.getElementsByTagName('div'); 
  var index = 0;

  var findNext = function() {
    var element = elements[index];
    index++;

    if (element.className === 'hi'){
      // Item found
      console.log('found:'+element);
    }

    if (index < elements.length) {
      setTimeout(findNext, 100);
    }
  };

  findNext();
}

findElements();

http://jsbin.com/zeseguribo/1/edit?html,js,console

bvaughn
  • 13,300
  • 45
  • 46
1
function sleep(milliseconds) {
    var start = new Date().getTime();
    while (1) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
} // sleep end

then call sleep(3000) in your loop.

Edit: This is a blocking way of delay. For async, non-blocking delay, you may use a recursive function.

marcieng
  • 1,021
  • 9
  • 14