kadri.r
kadri.r

Reputation: 37

get a function to be called periodically

I am trying to display a console log every 5 seconds and I am using this javascript code (for a chrome extension)

let t = document.getElementsByClassName('annonce_titre');
for (elt of t ){
   let titleLink = elt.getElementsByTagName('a');
   console.log(titleLink[0].href);

   setInterval(function(){console.log("Interval reached");}, 5000);
}

but it is showing all the messages at once without that 5 seconds interval , anyone has a clue why this is ?

Upvotes: 0

Views: 90

Answers (1)

Cat
Cat

Reputation: 4226

(Edited)
Since you clarified that you want to log something for each elt, here's a solution that uses a global count variable to track how many times the logging function has been invoked:

// Defines global variables
var t = document.getElementsByClassName('annonce_titre');
var count = -1;

// Calls logNextTitle at intervals (and gives it a name so we can clear it later)
var logger = setInterval(logNextTitle, 2000);


// The rest of the code defines our functions
function logNextTitle(){

  // Increments the global `count` variable
  count++;

  // Checks whether all the selected elements have been logged
  if(count < t.length){

    // Gets the title text and logs it
    const elt = t[count];
    const title = elt.getElementsByTagName('h2')[0];
    console.log(title.innerHTML);
  }
  else{

    // Calls clearLogger so we don't keep calling `logNextTitle` forever
    clearLogger();
  }
}

function clearLogger(){

  // Stops the `setInterval` code associated with the identifier `logger`
  clearInterval(logger);
  console.log("No more titles to log");
}
.annonce_titre{ background-color: green; }
<div class="annonce_titre">
  <h2>Title 1</h2>
  <a href="https://example.com">example.com</a>
</div>

<div class="annonce_titre">
  <h2>Title 2</h2>
  <a href="https://example.com">example.com</a>
</div>

<div class="annonce_titre">
  <h2>Title 3</h2>
  <a href="https://example.com">example.com</a>
</div>

Upvotes: 1

Related Questions