Sometimes, we want to reload an img every element 5 seconds using JavaScript.
In this article, we’ll look at how to reload an img every element 5 seconds using JavaScript.
How to reload an img every element 5 seconds using JavaScript?
To reload an img every element 5 seconds using JavaScript, we can use the setInterval
function.
For instance, we write:
<img src='https://picsum.photos/200/300'>
to add an img element.
Then we write:
const img = document.querySelector('img');
setInterval(() => {
img.src = 'https://picsum.photos/200/300'
}, 5000);
to select the img element with querySelector
.
And in the setInterval
callback, we set the src
property of the image to a URL.
We pass in 5000 milliseconds as the 2nd argument to run the callback every 5 seconds.
Conclusion
To reload an img every element 5 seconds using JavaScript, we can use the setInterval
function.