I have the following code that I found on the English site :
<html>
<head>
<script type="text/javascript">
var imageUrls = [
"https://via.placeholder.com/400x400?text=1", "https://via.placeholder.com/400x400?text=2", "https://via.placeholder.com/400x400?text=3", "https://via.placeholder.com/400x400?text=4", "https://via.placeholder.com/400x400?text=5", "https://via.placeholder.com/400x400?text=6"
];
var imageLinks = [
"https://es.stackoverflow.com/", "https://es.stackoverflow.com/", "https://es.stackoverflow.com/", "https://es.stackoverflow.com/", "https://es.stackoverflow.com/", "https://es.stackoverflow.com/"
];
function getImageHtmlCode() {
var dataIndex = Math.floor(Math.random() * imageUrls.length);
var img = '<a href=\"' + imageLinks[dataIndex] + '"><img src="';
img += imageUrls[dataIndex];
img += '\" alt=\"Stackoverflow.com\"/></a>';
return img;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(getImageHtmlCode());
</script>
</body>
</html>
It works as I want, with the only exception that sometimes it repeats the same image when refreshing the page. What is this about? Could you tell me if there is a bug that affects this behavior?
Thank you so much
It is basically due to this:
The Math.random() function generates a series of random numbers, surely you have had the bad luck that it has been repeated several times
As Lois6b suggests, you can prevent it from repeating by saving the data to
localstorage
orcookie
adding to your code something like:In
localstorage
you can save between 5MB and 10MB of information, it is saved locally, so it does not affect the server, so to speak it is cached .You can also use the session to save information until the tab or browser is closed.
Source: https://platzi.com/blog/local-storage-html5/
An example of a function that avoids repetition: