1

I'm currently using a setInterval function so that I can repeat text with an extra letter added to it for every 5 secs, hence I've set the time period for the setInterval function as 5000.

But I also want this function to be executed as soon as the page loads. To be clear the logic present inside the setInterval function should be executed as soon as the page loads and it should also be repeated for every 5 secs. Is it possible with setInterval function or else is there any other way to do it? Thank you in advance :)

setInterval(function(){
  var x = document.getElementById('sample');
  x.innerHTML = x.innerHTML+'L';
  },5000);
<p id="sample">Sample Text</p>
laurent
  • 88,262
  • 77
  • 290
  • 428
Harish
  • 1,193
  • 6
  • 22
  • 45

2 Answers2

4

Just make it a separate function, which you can then call right away. On top of that, you'll then have some nice reusable code:

function updateElement(){
    var x = document.getElementById('sample');
    x.innerHTML = x.innerHTML+'L';
}

setInterval(updateElement, 5000);

updateElement();
<p id="sample">Sample Text</p>
laurent
  • 88,262
  • 77
  • 290
  • 428
0

You can use named function run on init and call it each interval

setInterval(function someFunc() {
  var x = document.getElementById('sample');
  x.innerHTML = x.innerHTML + 'L';
  return someFunc
}(), 1000);
<div id="sample"></div>
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84