diff --git a/examples/function_memory_game/src/components/app.rs b/examples/function_memory_game/src/components/app.rs index 7e68e18fd..226c3399f 100644 --- a/examples/function_memory_game/src/components/app.rs +++ b/examples/function_memory_game/src/components/app.rs @@ -16,38 +16,45 @@ pub fn App() -> Html { let state = use_reducer(State::reset); let sec_past = use_state(|| 0_u32); let sec_past_timer: Rc>> = use_mut_ref(|| None); - let flip_back_timer: Rc>> = use_mut_ref(|| None); + let limit_flips_timer: Rc>> = use_mut_ref(|| None); let sec_past_time = *sec_past; - use_effect_with(state.clone(), move |state| { - // game reset - if state.status == Status::Ready { - sec_past.set(0); + use_effect_with(state.clone(), { + let limit_flips_timer = limit_flips_timer.clone(); + move |state| { + // game reset + if state.status == Status::Ready { + sec_past.set(0); + } + // game start + else if *sec_past == 0 && state.last_card.is_some() { + let sec_past = sec_past.clone(); + let mut sec = *sec_past; + *sec_past_timer.borrow_mut() = Some(Interval::new(1000, move || { + sec += 1; + sec_past.set(sec); + })); + } + // game over + else if state.status == Status::Passed { + *sec_past_timer.borrow_mut() = None; + *limit_flips_timer.borrow_mut() = None; + state.dispatch(Action::TrySaveBestScore(*sec_past)); + } + // match failed + else if state.rollback_cards.is_some() { + let cloned_state = state.clone(); + let cloned_rollback_cards = state.rollback_cards.clone().unwrap(); + *limit_flips_timer.borrow_mut() = Some(Timeout::new(1000, { + let limit_flips_timer = limit_flips_timer.clone(); + move || { + limit_flips_timer.borrow_mut().take(); + cloned_state.dispatch(Action::RollbackCards(cloned_rollback_cards)); + } + })); + } + || () } - // game start - else if *sec_past == 0 && state.last_card.is_some() { - let sec_past = sec_past.clone(); - let mut sec = *sec_past; - *sec_past_timer.borrow_mut() = Some(Interval::new(1000, move || { - sec += 1; - sec_past.set(sec); - })); - } - // game over - else if state.status == Status::Passed { - *sec_past_timer.borrow_mut() = None; - *flip_back_timer.borrow_mut() = None; - state.dispatch(Action::TrySaveBestScore(*sec_past)); - } - // match failed - else if state.rollback_cards.is_some() { - let cloned_state = state.clone(); - let cloned_rollback_cards = state.rollback_cards.clone().unwrap(); - *flip_back_timer.borrow_mut() = Some(Timeout::new(1000, move || { - cloned_state.dispatch(Action::RollbackCards(cloned_rollback_cards)); - })); - } - || () }); let on_reset = { @@ -58,6 +65,17 @@ pub fn App() -> Html { let on_flip = { let state = state.clone(); Callback::from(move |card| { + if limit_flips_timer.borrow().is_some() { + return; + } + + *limit_flips_timer.borrow_mut() = Some(Timeout::new(1000, { + let limit_flips_timer = limit_flips_timer.clone(); + move || { + limit_flips_timer.borrow_mut().take(); + } + })); + state.dispatch(Action::FlipCard(card)); }) };