简体   繁体   中英

JS setTimeout in while loop

Since setTimeout crashes in while loops.

I don't know if there is a way to do it but I am trying to make one. This is how it looks so far.

<script>
var send = true;
function sendit()
{
    alert("test");
    return true;
}
while(true)
{
    if(send == true)
    {
        send = false;
        setTimeout(function(){
            if(sendit() == true) {
                send = true;
            }
        }, 5000);
    }
}
</script>

Is it possible this way?

You haven't explained what you want your code to do. If you want it to alert "test" every 5 seconds then you need this:

<script>
function sendit()
{
    alert("test");
    // Call sendit() the next time, repeating
    setTimeout(sendit, 5000);
}
// Call sendit() the first time
setTimeout(sendit, 5000);
</script>

No need for a loop, just get the function to schedule itself again.

My understanding is that what you're trying to do is the equivalent of Thread.sleep(5000) in a language like Java or C#. That functionality does not exist in JavaScript. If you want to do something some amount of time after your function's execution, put it in a timeout, but one way or another, that first function will still complete in the same frame unless you're performing an enormous amount of work.

Currently, your code is setting a timeout on sendit() a practically-infinite number of times before it returns. Since JavaScript is single threaded, even if 20 seconds passed, it still wouldn't have finished your function and couldn't start looking up timeouts it needs to process. What you should be doing is something like having the inside of the timeout set another timeout, and remove the enclosing while(true) . That could allow for infinite, periodic behavior as I think you're looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM