How do we get realtime updates?

I’m trying to have a text change repetitively. It shall never be the same as long as the page has loaded. I understand that event listeners will listen for a specific event, whether it is a “click”, “onload”, etc. However, what about a event or some type of action were its just related to the idle website. While the user is staring at a screen, i’d like it to do some effect.

<a>Change me, constantly. Until user leaves the page.</a>

i would like that be change from 1 statement to the other. I’ve realize that creating an array that stores these statements but how can i make it so its constantly updating?

Thanks in advance.

You’re looking for setInterval

So the javascript will run by setting a specific clock? Is that the only way?

AFAIK if you don’t want the alternating content to change in response to any event being fired, the only thing left is to use time.

How would i get to use it then?

setInterval(slowAni, 1000);

function slowAni(){
 //some code
}

Am i to assume that, the above code will run on its own after the page has loaded, every 1000 milliseconds or am i doing it all wrong?

Nope you’re doing it right. This is very similar to a “heartbeat” where a site keeps checking back with the server to tell it that the user is still alive. It’s more common than you’d think.

I was curious instead of calling the function directly, what would be the benefit of initializing it to a variable.
For Example:

var time = setInterval(slowAni, 1000);

function slowAni(){
 //some code
}

also being that javascript is functional, shouldnt the function be placed before the variable declaration:

function slowAni(){
 //some code
}
var time = setInterval(slowAni, 1000);

Or does it not make a differences here.

It doesn’t make a difference here. The variable will let you do things to it or read it later, like stopping it using clearInterval.

clearInterval(time)

The placement of the function doesn’t matter to the code as long as you’re not setting the function to a variable.

okay i see, perfect i’ll make sure to initialize it to a variable.

Thanks for the help if i encounter any other issues, be sure that i shall return!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.