Repeat query with javascript

1

I need to update a div constantly and however this code below only updates once, I would like instructions how to do it always update to a certain time so that the same action be repeated countless 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>
    
asked by anonymous 25.05.2015 / 00:39

1 answer

1

Change your code to:

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

But I suggest that instead of simulating the click, encapsulate a function with the code you want to execute on the click and set it on setInterval :

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

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

window.setInterval(atualizarDiv, 2000);

The setInterval function 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 stop executing this intervalo , use the clearInterval function by passing the handle:

var idIntervalo = window.clearInterval
// para interromper a execução
window.clearInterval(idIntervalo);
    
25.05.2015 / 01:05