Run function with Javascript/ Jquery timer

Asked

Viewed 3,433 times

1

I need help creating a function in javascript/jquery to do the following:

  • When user accesses my site, starts time counter.
  • If the person tries to close the browser window/tab before a certain time, e.g. 5 sec, then performs a function.
  • Now if the person spends more than 5 sec on the site the function will not be executed.
  • Have you tried using beforeunload? Here you explain more or less how it is http://stackoverflow.com/questions/1631959/how-to-capture-the-browser-window-close-event#1632004

1 answer

1


See if that’s it :)

var contador = 5;

setTimeout(temporizador,1000);

function temporizador() {
  if(contador > 0){
    setTimeout(temporizador,1000);
  } else {
    window.onbeforeunload = null;
  }
  document.getElementById('tempo').innerHTML = contador;
  contador--;
}

window.onbeforeunload = function() {
  // chama função
  return "Chamar uma função antes do tempo";
}
<p> Tempo restante: 
    <span id="tempo" />
</p>

  • Exactly this Maicon Carraro, thanks!

Browser other questions tagged

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