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));
  }
}
0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

sleeping in javascript is really bad - it causes the UI to lock up.
I thought he may need a blocking delay.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.