JavaScript - Do something every n seconds

Zachary Elkins picture Zachary Elkins · Nov 21, 2016 · Viewed 28.3k times · Source

I am fairly new to JavaScript, and I am learning it through p5 and videos by Daniel Shiffman.

I've been looking for a way to update a program every minute or so that checks a weather api, so I don't have to refresh the page myself.

I am aware that there are already answers to this question on here, but none of them make sense to me, as I am very new to JS.

So if you could answer it with an ELI5 ("Explain it like I'm five") description that would great.

Answer

sidewalksalsa picture sidewalksalsa · Nov 21, 2016

setInterval() is your easiest option.

Take a look at this simple example:

// Will execute myCallback every 0.5 seconds 
var intervalID = window.setInterval(myCallback, 500);

function myCallback() {
 // Your code here
}

More information and more examples can be found here: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval (https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval)