views:

76

answers:

3

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?
+3  A: 

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() or 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:


Now that you know why a blocking sleep function won't work, check out @Tomalak's link for a few solutions using setTimeout() or setInterval().

Daniel Vassallo
ya i agreed but any suggestion for my problem
Paniyar
@Paniyar: Let me add some further info... (updating my answer)
Daniel Vassallo
You cannot run asynchronous code (like timeouts) synchronously in JavaScript. Period. The `sleep` function cannot exist.
bobince
+2  A: 

This is quite simple and also has been answered before. See the answers to this question:

Tomalak
+1  A: 

You're complaining about setTimeout and setInterval, but then describing how you are using them badly. Either user setTimeout not in a loop and have it call another setTimeout if there is more to do, or use setInterval and call clearInterval after a maintained count is reached.

Jon Hanna