How to make setTimeout run "infinitely"

1

I need a function to run every 2 minutes. I found this link a solution for my need:

Link

The Code below, calls an alert after 5 seconds when the mouse is stopped.

Note
I put 5 seconds to save time on the test.

<script type="text/javascript">
$(function() {
    timeout = setTimeout(function() {
       alert('executa função');
    }, 5000);
});

$(document).on('mouseover', function() {
    if (timeout !== null) { 
        clearTimeout(timeout);
    }

    timeout = setTimeout(function() {
        alert('executa função');
    }, 5000);
});
</script>

What I need:
I need this script to work the same way only in an infinite loop, where every 5 seconds the alert will be called.

I tried to embrace the code with:

while(0 = 0){

}

But it did not work ...

How do I then run my function automatically every 5 seconds automatically?

    
asked by anonymous 03.07.2015 / 16:26

2 answers

2

For the event to occur infinitely without the mouseover, simply remove it. See:

function Temporizador(initiate) {
    if (initiate !== true) {
        alert("Olá mundo");
    }
    setTimeout(Temporizador, 5000);
}

$(function() {
    Temporizador(true);
});

If you call Temporizador(true); with true, it does not execute the first alert , but only every 5 seconds.

    
03.07.2015 / 16:43
2

Use setInterval , which does basically the same thing but repeating the each period

<script type="text/javascript">
var timeInterval = null;
$(document).on('mouseover', function() {
    if (timeInterval !== null) { 
        clearInterval(timeInterval);
    }

    timeInterval = setInterval(function() {
        alert('executa função');
    }, 5000);
});
</script>
    
03.07.2015 / 16:33