How to make setTimeout run "infinitely"

Asked

Viewed 2,392 times

1

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

Link

The Code below, calls an Alert after 5 seconds while leaving the mouse stationary.

Observing
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 will be called the Alert.

I tried to embrace the code with:

while(0 = 0){

}

But it didn’t work...

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

  • this same...leave it like: counted 5s ->calls Function, counted +5s -> calls Function...

2 answers

2

Use setInterval, which does basically but same thing, but repeating every 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>
  • Thanks for the help, but and how do I make it happen automatically, whether the mouse is stopped or not...

  • 1

    leave setInterval out of the event. For example, where I assign var timeInterval = null; do var timaInterval = setInterval(Function() { Alert('executes function'); }, 5000);

  • Perfect, this way works as I needed. Thank you very much

  • You could also use $(document).one( to run only once and thus save a global variable.

2


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

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

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

Call the Temporizador(true); with true, it does not perform the first alert, but only every 5 seconds.

  • 1

    Bingo! worked perfectly. Thank you very much

Browser other questions tagged

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