Question: I'm aware of both `setInterval` and `setTimeout` functions but it's not suitable for my case, because I need to create an `img` DOM element in the interval of 7 seconds.

* The count of images are not predefined (varies daily).

When I use `setInterval`, I cannot *completely* stop it after certain limit (daily count). [`clearInterval` clears iterations only] 

When I use `setTimeout` inside loop (daily count), it never delays. So the only possibility is a sleep function. Can anyone help for this situation?

* What's the best way to implement a sleep function JavaScript?

Answer: 
> 
> What's the best way to implement a sleep function JavaScript?
> 
> 
> 

JavaScript code has to be non-blocking, because any code that blocks, like a loop that waits for something to happen, will make the whole browser unresponsive. JavaScript in web browsers not only runs in a single thread, but it actually shares the same thread with the page rendering and UI.

The solution is to use timers: [`setTimeout()`](https://developer.mozilla.org/en/DOM/window.setTimeout) or [`setInterval()`](https://developer.mozilla.org/en/DOM/window.setInterval). These functions are non-blocking; they return immediately. They attach a callback function to a timeout event that will get triggered some time in the future. The JavaScript code terminates execution soon after the `setTimeout()` function is called, so the users would still be able to use the browser. Then when the timeout is triggered, the previously defined callback is invoked, and your code is interpreted. This is the only practical way to handle "delays" in JavaScript. 

In addition, here's an interesting article on how JavaScript timers work:

* [How JavaScript Timers Work](http://ejohn.org/blog/how-javascript-timers-work/) by John Resig

---

Now that you know why a blocking sleep function won't work, check out [@Tomalak's link](https://stackoverflow.com/questions/3845972/javascript-sleep-function/3845996#3845996) for a few solutions using `setTimeout()` or `setInterval()`.
This is quite simple and also has been answered before. See the answers to this question: 

* [Want a javascript function to run every minute, but max 3 times.](https://stackoverflow.com/questions/1245617/want-a-javascript-function-to-run-every-minute-but-max-3-times)