JavaScript | Atomics.wait() Method

Among the Atomic Operations, there is an inbuilt operation Atomics.wait() in JavaScript is used to verify whether a given position in an Int32Array still contains a given value and if so sleeps, awaiting a wakeup or a timeout. The Atomics.wait() operation returns a string which is either “ok”, “not-equal”, or “timed-out”. The integer typedarray, index, and the value are passed as an argument to the function and timeout is also an argument but it is optional.

Syntax:

Atomics.wait(typedArray, index, value, timeout)

Parameters: This method accept four parameters as mentioned above and described below:

  • typedarray: This parameter specifies a shared integer typed array Int16Array.
  • index: This parameter specifies the position in the array, typedArray to wait on.
  • value: This parameter specifies the expected value to test.
  • timeout: This parameter is an optional parameter. It is time to wait in milliseconds.

Return value: The Atomics.wait() method returns the String which is either “ok”, “not-equal”, or “timed-out”.

Examples:



Input: arr[0] = 5
        Atomics.wait(arr, 0, 0, 1)
Output: not-equal

Input: arr[0] = 4
        Atomics.wait(arr, 1, 0, 1)
Output: time-out

Below programs illustrate the Atomics.wait() method in JavaScript:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

var buf = new SharedArrayBuffer(1024); 
var arr = new Int32Array(buf); 
  
arr[0] = 5; 
console.log(Atomics.load(arr, 0)); 
console.log(Atomics.and(arr, 0, 9)); 
console.log(Atomics.wait(arr, 0, 0, 1)); 
console.log(Atomics.load(arr, 0)); 

chevron_right


Output:

5
5
not-equal
1

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

var buf = new SharedArrayBuffer(1024); 
var arr = new Int32Array(buf); 
  
arr[0] = 5; 
console.log(Atomics.load(arr, 0)); 
console.log(Atomics.and(arr, 0, 9)); 
console.log(Atomics.wait(arr, 1, 0, 1)); 
console.log(Atomics.load(arr, 0));

chevron_right


Output:

5
5
time-out
1

Exceptions:

  • If the typedArray is not a shared Int32Array then the Atomics.wait() operation throws a TypeError.
  • If the index used as an argument to the Atomics.wait() operation is out of the bound in the typedArray then the Atomics.store( ) operation throws a RangeError.

full-stack-img

My Personal Notes arrow_drop_up

Small things always make you to think big

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.