I am currently working on a Worlde clone written in JavaScript. I used the rapid API to fetch the five letter word in a function called getWord.
I also used a function called onceADay
so the getWord function only gets called once. At the end of the onceAday function, I call location.reload()
, so once a new word has been loaded, the website should refresh itself, hence you can start the game again. My problem is that the reload page function runs so quickly that it doesn’t let the fetch get a new word. I tried async/await but it did not work. I also tried to delay to refresh.. but it doesn't work reliably. I also tried to save the last word in a localObject
and implement a while loop in the onceADay function.. so while the previousword
is equal to current word it should repeat the fetch. but it just crashed the whole site. At this point I am clueless about how I could fix it. I just run out of options here. I am quite new to JavaScript, so I am hoping maybe someone who has more experience could give me a solution. I got the whole project on my git repo ( https://github.com/dodoo86/WordleJS )
Also, here’s the functions I mentioned above.
This is how I fetch the word using async await
async function fetchWordJSON() {
const response = await fetch('https://squirrelle.onrender.com/word');
const word = await response.json();
return word;
}
Than I check if a day passed
function hasOneDayPassed() {
var date = new Date().toLocaleDateString();
if (localStorage.yourapp_date == date)
return false;
localStorage.yourapp_date = date;
return true;
}
Than if so, it should run the following things once a day
function runOncePerDay() {
if (!hasOneDayPassed()) return false;
fetchWordJSON().then(word => {
word;
localStorage.setItem("wor", word)
});
console.log("Word ", localStorage.getItem("wor"));
localStorage.setItem("Won", "false");
wordle = localStorage.getItem("wor").toUpperCase();
console.log("WordUPSCALE ", wordle);
checkLastWinDates();
localStorage.setItem("gamePlayed", "false");
location.reload();
}
In this way it refreshes the site before it could fetch, so the word remains the same when i set the clock to a next day. If I do the reset with a delay, it works quite unreliably. I added 2000 minisec delay and if the backend is a bit slower then usual it doesn’t refresh the word if its quicker it does. So I would need a bulletproof method to make sure the word always refresh before the page.