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.

SiddP
  • 1,603
  • 2
  • 14
  • 36
  • `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 – murli2308 Jan 14 '16 at 06: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. – SiddP Jan 14 '16 at 06:37
  • http://stackoverflow.com/questions/4548034/create-a-pause-inside-a-while-loop-in-javascript ....similar to this question – Mayur Lunawat Jan 14 '16 at 06:47

5 Answers5

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.

Thayne
  • 6,619
  • 2
  • 42
  • 67
  • 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. – SiddP Jan 14 '16 at 06:42
  • what about recursively calling setTimeouts? Also, you can cancel an interval with clearInterval if that helps. – Thayne Jan 14 '16 at 16:50
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
Yair Kukielka
  • 10,686
  • 1
  • 38
  • 46
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);
}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • well the above snipped do not run endlessly.It runs single time after 15 secs and then stop . – SiddP Jan 14 '16 at 06:45
  • @user3069962 check again and let me know – gurvinder372 Jan 14 '16 at 06:45
  • 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. – SiddP Jan 14 '16 at 06:52
  • `setTimeout` is not evil but you do have to be careful _how_ you use it. – Andy Jan 14 '16 at 06:54
  • @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. – gurvinder372 Jan 14 '16 at 06:56
  • @Andy/gurvinder372 . I would do that but my problem is when I close the tab my flow do not come to the logic where tab view is written so it is been difficult to close them. So if I dont use setInterval/Timeout is there any thing else in javascript which will allow me to interate infinitely through a loop at certain intervals till my tab is open. – SiddP Jan 14 '16 at 07:04
  • @user3069962 which tab are you talking about? is this a browser tab or some tab in your app? – gurvinder372 Jan 14 '16 at 07:06
  • @gurvinder. No it is not browser tab. I am talking about the tabs inside my application.I am using openui5 framework. – SiddP Jan 14 '16 at 07:08
  • @user3069962 in that case you need to `either` check the "close of tab" as a terminating condition inside myMethod `or` clearTimeout at the close event of the tab – gurvinder372 Jan 14 '16 at 07:12
0

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

Jitin Kodian
  • 471
  • 4
  • 14
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

Andy
  • 61,948
  • 13
  • 68
  • 95