Repeat query with javascript

Asked

Viewed 670 times

1

I am needing to update a div constantly and however this code below only updates once, I would like instructions on how to update it always at a certain time so that the same action is repeated numerous times.

 <!DOCTYPE html>
    <html>
    <head>
    <title>Refresh sem atualizar página</title>
    <meta charset="utf-8">
    <script src="jquery.js" type="text/javascript"></script> 
        <body>

        <div id="panel">teste</div>
        <input id="changePanel" value="Change Panel" type="hidden">

        <script>
        $("#changePanel").click(function() {
            var data = "testando";
            $("#panel").hide().html(data).fadeIn('fast');
        });

        window.setTimeout(function(){
           document.getElementById("changePanel").click();
        }, 2000);
        </script>
        </body>
</html>
  • That one data comes from where? if it is new data that you search via server that should be done in another way.

1 answer

1


Change your code to:

window.setInterval(function(){
       document.getElementById("changePanel").click();
 }, 2000);

However, I suggest, instead of simulating the click, encapsulate a function with the code you want to run in the click and configure it in the setInterval:

function atualizarDiv() {
    var data = "testando";
    $("#panel").hide().html(data).fadeIn('fast');
}

$("#changePanel").click(atualizarDiv);

window.setInterval(atualizarDiv, 2000);

The function setInterval receives as parameters a callback and the time in milliseconds of the interval that must execute the callback of the first parameter and returns an identifier of that intervalo. If you need to interrupt the execution of this intervalo, use the function clearInterval passing as argument the identifier:

var idIntervalo = window.clearInterval
// para interromper a execução
window.clearInterval(idIntervalo);
  • That’s exactly what it was, thank you very much.

Browser other questions tagged

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