# base/wait (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/base/wait/

비동기 기다리기. (원본 base/wait.js 의 Wait.seconds, Wait.nextFrame)
- 엔진 작업(Engine::spawn_task, spawn_scene_task) 안에서 await 한다. 엔진은 작업을 프레임마다 한 번 폴링하므로,
  아직이면 스스로 깨워 다음 프레임에 다시 본다.
- seconds 는 원본처럼 벽시계 시간이다. (원본 setTimeout(seconds * 1000), 시간 배율(time_scale)을 곱하지 않고 멈춤에도 흐른다)
  부른 때부터 잰다. (원본도 seconds 를 부를 때 setTimeout 을 건다) 웹은 performance.now(), 데스크탑은 std::time 이다. (web_time::Instant)
  원본 setTimeout 이 0 초라도 다음 차례에 부르듯, 부른 뒤 엔진의 폴링 차례가 적어도 한 번 지나야 끝난다. (seconds(0) 은 한 번 쉬고 끝난다)
  시간이 이미 지난 뒤에 await 하면 원본처럼 바로 끝난다. 시간은 원본 setTimeout 처럼 밀리초를 WebIDL long(ToInt32)으로 바꾸고 음수는 0 이다.
  (NaN 과 무한은 0, 2^31 밀리초 이상은 2^32 로 감겨 돈다)
- next_frame 은 원본(requestAnimationFrame 의 Promise 를 await)처럼 다음 프레임까지 기다린다. 부른 뒤 엔진의 폴링 차례가 한 번 지나면 끝난다.
- 폴링 차례 번호는 스레드 하나에 하나이고, 엔진이 폴링 차례마다 올린다. (core/task.rs 의 poll_tasks)

## WaitSeconds (struct) (Clone, Copy, Debug, Future)

시간 기다리기 퓨처. (seconds 가 돌려준다)

예제: 먼저 불러 두고 다른 일을 한 뒤 기다리기 (부른 때부터 잰다)

```rust
use vanilla::{wait, Engine};

fn show_loading(engine: &Engine) {
	engine.spawn_task(move |mut engine_context| async move {
		let minimum_wait: wait::WaitSeconds = wait::seconds(2.0);
		engine_context.with(|engine| engine.set_title("Loading"));
		minimum_wait.await;
		engine_context.with(|engine| engine.set_title("Ready"));
	});
}
```

## NextFrame (struct) (Clone, Copy, Debug, Future)

한 프레임 기다리기 퓨처. (next_frame 이 돌려준다)

예제: 다음 프레임까지 기다리고 프레임 번호 읽기

```rust
use vanilla::{wait, Engine};

fn read_next_frame_number(engine: &Engine) {
	engine.spawn_task(move |mut engine_context| async move {
		let start_frame_number = engine_context.with(|engine| engine.get_frame_number());
		wait::next_frame().await;
		let next_frame_number = engine_context.with(|engine| engine.get_frame_number());
		println!("{} {}", start_frame_number, next_frame_number);
	});
}
```

## Functions and constants

- `pub fn seconds(seconds: f64) -> WaitSeconds` (method, since 0.4.0): 일정 시간 동안 비동기 대기. (원본 Wait.seconds, 벽시계 초)
  - `seconds` f64: 기다릴 시간. (벽시계 초, 시간 배율과 멈춤에 상관없다. 밀리초로 내린 뒤 음수, NaN, 무한은 0)
  - returns WaitSeconds: 부른 때부터 그 시간이 지나고 엔진의 폴링 차례가 한 번 이상 지나야 끝나는 퓨처. (엔진 작업 안에서 await 한다)

  예제: 1 초마다 창 제목을 바꾸는 카운트다운

  ```rust
  use vanilla::{wait, Engine};
  
  fn start_countdown(engine: &Engine) {
  	engine.spawn_task(move |mut engine_context| async move {
  		for count in (1..=3).rev() {
  			engine_context.with(|engine| engine.set_title(&format!("{}", count)));
  			wait::seconds(1.0).await;
  		}
  		engine_context.with(|engine| engine.set_title("Go"));
  	});
  }
  ```

- `pub fn next_frame() -> NextFrame` (method, since 0.4.0): 한 프레임 비동기 대기. (원본 Wait.nextFrame)
  - returns NextFrame: 부른 뒤 엔진의 폴링 차례가 한 번 지나면 끝나는 퓨처. (엔진 작업 안에서 await 한다)
