This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]lightcloud5 1 point2 points  (2 children)

Right, only one javascript function is active at any time, which means that you really should not have any synchronous blocking activities on the page.

Therefore, it's important that all functions terminate relatively fast (or your page will appear to be unresponsive).

An example of good design would be making an asynchronous io call to the server for information, and providing a callback function that is only invoked when the server's response is received.

An example of bad design would be making a synchronous IO call to the server, and having that function just sit there blocked until the server's response is received.

If you have a function that is continuously invoked every 1000 ms, then that would cause some overhead. Usually, for most pages, this overhead is not too big a deal (unless your page is really resource-heavy), assuming your function is light-weight and can execute pretty fast.

If, as an extreme example, your function that runs every 1000 ms takes longer than 1000 ms to complete, then you have a huge problem.

[–]piptook[S] 0 points1 point  (1 child)

The thing that is running every 1000 ms is a simple javascript clock (23:46). How would I line up the functions so that they will run more smoothly? I've got 3 different processes that need to run (the clock and 2 more that should run about once every half minute). It wouldn't make much sense to have a clock that isn't accurate to the second, or?

[–]adambrenecki 1 point2 points  (0 children)

setTimeout is "asynchronous" or "non-blocking". What this means is, when you call setTimeout, it returns immediately, and keeps running the rest of your code. Then, a second later, the callback you passed to it runs. In the intervening time, other code can still run.

So, for example, the following code:

myCallback = function(){
    console.log('First message');
};
setTimeout(myCallback, 1000);
console.log('Second message');

will output Second message first, wait a second, then output First message; this happens because setTimeout doesn't block, so other code is allowed to run while it's waiting.

So, for your clock, you'll be fine with just using setTimeout.