1

I have a function update() that is called at 5 second intervals:

setInterval(function() {
    update();
}, 5000);

My objective, however, is to call the function immediately on load and then every 5 seconds after that. How would one achieve this in javascript or jQuery ?

the_darkside
  • 5,688
  • 7
  • 36
  • 83
  • 3
    `window.onload = function() { update(); setInterval(update, 5000); };` – Jared Smith Sep 05 '17 at 16:55
  • `window.addEventListener('load', update)` would trigger it on load. Why worry is the interval triggers it slightly sooner than 5 secs after? Otherwise, write a load function that calls update and sets the interval and attach it to the load events as before. – somethinghere Sep 05 '17 at 16:56

2 Answers2

4

You could do something like this.

Simply call update immediately, then add your timeout callback after that.

update();
setInterval(update, 5000);
Kulix
  • 394
  • 2
  • 12
2

Like this:

update();
setInterval(update, 5000);

This would call update() immediately.

If by "on load" you mean you want to wait until the page is loaded, you can do this in jQuery (since you asked about jQuery):

$(function () {
    update();
    setInterval(update, 5000);
});
JLRishe
  • 90,548
  • 14
  • 117
  • 150