Answer the question
In order to leave comments, you need to log in
The interval (setInterval) slows down the work very much. What can be done to optimize?
I make a game like vkcoin (as a practice), I use Vue js, express, mongo DB, with the help of setInterval I dispatch the vuex function of sending data to the server every second, but if the game is active for a long time, it starts to lag, and also, after 7 or more seconds, starting to refresh the page, it will be updated forever until the page refresh is canceled (because of this, some kind of error occurs with fetch) and within 7 seconds, again, I can refresh the page normally. What could be the problem?
//Game.vue - interval
this.updateInterval = setInterval(async () => {
await this.$store.dispatch('sendData', {
user: this.userData,
data: this.globData
})
}, 1000)
//vuex model gameLogic - sendData()
async sendData(ctx, {user, data}) {
let boost = 0
for (let GPU of user.data.GPUs) {
for (let dGPU of data.GPUs) {
if (GPU.title === dGPU.title) {
boost += GPU.count * dGPU.speed
break
}
}
}
for (let CPU of user.data.CPUs) {
for (let dCPU of data.CPUs) {
if (CPU.title === dCPU.title) {
boost += CPU.count * dCPU.speed
break
}
}
}
user.data.balance += boost
const res = await request('/update', 'POST', user)
}
//server
app.post('/update', async (req, res) => {
let { email, data } = req.body
User.collection.updateOne({email}, {$set: {"data.balance": data.balance}})
})
//request function
async function request(url, method = 'GET', data = null) {
try {
const headers = {}
let body
if (data) {
headers['Content-Type'] = 'application/json'
body = JSON.stringify(data)
}
const response = await fetch(url, {
method,
headers,
body
})
return await response.json()
} catch (e) {
console.warn('Error: ', e.message)
}
}
Answer the question
In order to leave comments, you need to log in
My friend, yes, you need websockets, you can’t hammer on the back with Ajax.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question