Repeat action every second #PHP

Asked

Viewed 151 times

0

And creating a project and I needed that when the user clicked on the button "START POINTS" the Code of PHP is activated, every 10 seconds he gains 1 point on database and this was repeated until the user clicked on the "STOP POINTS".

I’ve done the points part, but how do I do the "timer"?

It would be like this:

Every 10 seconds it runs:

$sql_soma = mysql_query("UPDATE users SET cpoints = cpoints+1 WHERE users.user_email = '$e_mail'");
  • And better do it with ajax bro.

  • If the logic is to start the count and stop when you click on "STOP POINTS", , you could just record the time you started and add up the time and points when you stop. Save requests and miscellaneous processes.

1 answer

2


So, you could do using only Javascript, and then take the amount with PHP and save to the database. So you wouldn’t need to run querys every little bit to update the points in the database.

See a small example I made here using the setInterval of Javascript.

let iniciar = document.getElementById('iniciar');
let finalizar = document.getElementById('finalizar');
let pontuacao = 0;
let contador = 0;
let interval = null;

iniciar.addEventListener('click', function () {
  console.log('iniciou, espere os 10 segundos.');
  interval = setInterval(contaPontos, 10000);
});

finalizar.addEventListener('click', function () {
  console.log('parou');
  clearInterval(interval);
});

function contaPontos() {
	contador++;
  document.getElementById("pontos").innerHTML = contador;
}
<button type="button" id="iniciar">Iniciar Jogo</button>
<button type="button" id="finalizar">Finalizar jogo</button>
<p id="pontos"></p>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.