1
    while(true){
        window.setTimeout(function() {
            myMethod()
        }, 15000);
        }
        function myMethod() {
            alert("repeat");
        }

Above piece of code is written to execute mymethod infinitely but in certain intervals but once I run the code my browser hangs and the repeat pop up generates constantly but the time here is 15 secs. I wanted to avoid setInterval so using this technique for my purpose.

3
  • while(true) condition goes in infinite loop. so for every loop call it call your method and infinitely it calls the alert. What exactly you want to achieve? and both setTimeout and setInterval are not good for performance Commented Jan 14, 2016 at 6:33
  • I have an ajax snippet which fetches data from DB and displays in the page. Now I want it to execute after every 5 minutes i.e. the page gets refreshed with new data every 5 minutes. I am using openui5 with tabs so setInterval actually do not work as when I close tab it still works. So hence above logic where I iterate an infinite loop and after every 5 minutes in this eg 15 secs I want to execute my code to refresh page here just taken alert to check if it works. Commented Jan 14, 2016 at 6:37
  • stackoverflow.com/questions/4548034/… ....similar to this question Commented Jan 14, 2016 at 6:47

5 Answers 5

4

Javascript is single threaded (with the exception of web workers, but that is irrelavent to this example so we will ignore it). What this means is that setTimeout actually does is schedules some code to be executed some time in the future, after at least some amount of time, but only when the browser has stopped whatever else it was doing on the rendering thread at the time, which could be rendering html, or executing javascript.

So, the code in the setTimeout can't execute until the while loop (and whatever code contains it) finishes and returns control back to the browser. But it is an infinitely loop, so control is never returned to the browser and the code in the setTimeout is never executed.

In fact, a common idiom in javascript is to use a setTimeout with a timeout of 0 (or possibly 1) so that some code will be executed as soon as possible after the code for the current event has executed, and typically after the browser has rendered any html changes that were made by javascript.

I don't know what your exact use case is, but you can probably do what you want either using a setInterval (which is like setTimeout but is called repeatedly at an interval), or by calling setTimeout inside the function in the setTimeout to achieve an infinite loop with recursion, but letting the browser perform other tasks in between iterations.

Sign up to request clarification or add additional context in comments.

2 Comments

setInterval do not work for me as I am using the code in tabs inside of an application so even if I close tab it do not kill setInterval and the pop still comes once the tab is killed.
what about recursively calling setTimeouts? Also, you can cancel an interval with clearInterval if that helps.
1

With async/await, if you want to run an infinite loop of a function being ran every 3 seconds you can do this:

const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

(async (delay) => {
  while (true) {
      await wait(delay);
      myFunc();
  }
}(3000); // 3 seconds

Comments

0

setTimeout is executed asynchronously. So in your code, the infinite loop is creating an infinite setTimeouts each with a delay of 15 secs.

Comments

0

but once I run the code my browser hangs

it will because you are endlessly creating setTimeout() requests by doing while(true) since it will not wait for 15 secs before doing next iteration of while

if you want to keep alerting something every 15 sec then try

window.setTimeout( myMethod, 15000);
function myMethod() 
{
    alert("repeat");
    window.setTimeout( myMethod, 15000);
}

9 Comments

well the above snipped do not run endlessly.It runs single time after 15 secs and then stop .
@user3069962 check again and let me know
Voila! However it still is not solving my problem I thought it might solve. setTimeout is as evil as setInterval. The pop up still comes even if I close my tab of my application. Apart from setInterval and setTimeout. Is there any other way around to get this working.
setTimeout is not evil but you do have to be careful how you use it.
@user3069962 does the popup comes only once after you close your tab? Anyways setTimeout and setInterval are not evil unless you are not clearing them using clearTimeout and clearInterval. It is like saying that recursion is evil if you don't terminate the same.
|
0

The trick here, I think, would be to have the check inside the setTimeout and use clearTimeout when the condition is met. Here's an example that logs a count to the console every 1.5 seconds until 0.

function looper(time) {
  if (time > 0) {
    console.log(time);
    var timer = setTimeout(looper, 1500, --time);
  } else {
    clearTimeout(timer);
  }
}

looper(10);

You would obviously change the condition to that required by your program.

DEMO

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.