0

I want to create a real thread which manages some operations in javascript. After several search, i found 'Web Workers', 'setTimeout' or 'setInterval'.

  • The problem is that 'Web Workers' don't have access to global variables and therefore can't modify my global arrays directly (or i do not know how).
  • 'setTimeout' is not really what i need.
  • 'setInterval' sets my problem, however it is probably that after many times my operations could last longer. Therefore i am afraid that two interval overlaps.

Finally i need a infinite loop which executes a series of operations once after another. Does it exist or do I have to content myself with 'setInterval'? Is there an alternative with jQuery or other? If it is not, is what I can expect in the near future to see the developer make it available?

8
  • 1
    Javascript is single-threaded. You can't do that. What are you trying to do? Commented Nov 22, 2015 at 17:13
  • 1
    setInterval will not allow intervals to "overlap". At worst they will occur back-to-back with 0 delay, which can happen if an interval event fires during the execution of a previous interval. See ejohn.org/blog/how-javascript-timers-work Commented Nov 22, 2015 at 17:16
  • setInterval is internally the same as setTimeout except that setTimeout only runs once, but setInterval will restart the time after the end of each execution. Commented Nov 22, 2015 at 17:19
  • You probably have several options to perform your operations. It all depends on what are those "some operations" and "series of operations one after another", and what you try to avoid. Adding those details in your question would help people understand what you try to achieve and propose some solutions. Commented Nov 22, 2015 at 17:19
  • 1
    @SLaks (Dons pedantry hat) JavaScript isn't single-threaded. The language is nearly silent on the topic of threading, and there are multi-threaded JavaScript engines (Rhino and Nashorn, for instance). JavaScript on web browsers only runs a single thread per global context, but even then, you can have multiple threads, each with its own global context, via web workers. (Doffs pedantry hat) ;-) Commented Nov 22, 2015 at 17:31

2 Answers 2

3

I'm going to assume you're talking about in a web browser.

JavaScript in web browsers has a single main UI thread, and then zero or more web worker threads. Web workers are indeed isolated from the main UI thread (and each other) and so don't have access to globals (other than their own). This is intentional, it makes both implementing the environment and using it dramatically simpler and less error-prone. (Even if that isolation weren't enforced, it's good practice for multi-threaded programming anyway.) You send messages to, and receive messages from, web workers via postMessage and the message event.

JavaScript threads (the main UI thread and any web workers) work via a thread-specific task queue (aka "job queue"): Anything that needs to happen on a JavaScript thread (the initial run of the code when a page loads, handling of an event, timer callbacks [more below]) adds a task to the queue. The JavaScript engine runs a loop: Pick up the next task, run it, pick up the next, run it, etc. When there are no tasks, the thread goes quiet waiting for a task to arrive.

setTimeout doesn't create a separate thread, it just schedules a task (a call to a callback) to be added to the task queue for that same thread after a delay (the timeout). Once the timeout occurs, the task is queued, and when the task reaches the front of the queue the thread will handle it.

setInterval does exactly what setTimeout does, but schedules a recurring callback: Once the timeout occurs, it queues the task, then sets up another timeout to queue the task again later. (The rules around the timing are a bit complex.)

If you just want something to recur, forever, at intervals, and you want that thing to have access to global variables in the main UI thread, then you either:

  1. Use setInterval once, which will set up recurring calls back to your code, or

  2. Use setTimeout, and every time you get your callback, use setTimeout again to schedule the next one.

From your description, it sounds as though you may be calling setInterval more than once (for instance, on each callback), which quickly bogs down the thread as you're constantly telling it to do more and more work.

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

1 Comment

@Rodrigue: I don't see any multi-threading proposals on the current list. That could change, of course, but I'm not sure the language needs much in the way of threading semantics; that's primarily an environment thing. To the extent the language needs them, I think the current spec covers it (basically: run to completion, promise callbacks are async).
1

The last thing is easy: webworker start their work when they get a message to (onmessage) and sit idle otherwise. (that's highly simplified, of course).

Global variables are not good for real multi-threading and even worse with the reduced thing JavaScript offers. You have to rewrite your workers to work standalone with only the information given.

Subworkers have a messaging system which you might be able to make good use of.

But the main problem with JavaScript is: once asynchronous always asynchronous. There is no way to "join" threads or a "wait4" or something similar. The only thing that can do both is the XMLHttprequest, so you can do it over a webserver but I doubt the lag that causes would do any good. BTW: synchronous XMLHttprequest is deprecated says Mozilla which also has a page listing all of the way where a synchronous request is necessary or at least very useful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.