1

Let's say I have a variable that can be modified by two functions: one is invoked periodically via setTimeout and the other is an event handler:

var a = [];
function foo()
{
   var x = a.pop();
   // do something with x...
   setTimeout(function(){ foo(); }, 1);
}
//...
someElement.addEventListener("keypress", function(e){ a.push("some value"); }, true);

Is this code safe? Do the event listener and foo run in the same thread or in different threads? If they run in different threads, does the javascript runtime have to guarantee that access to a is synchronized?

1 Answers1

3

JavaScript is always single threaded in browsers. You will have no problems with your event listener.

I will refer you to this excellent answer by user Jonathon

Community
  • 1
  • 1
Jean-Bernard Pellerin
  • 12,556
  • 10
  • 57
  • 79