setInterval / clearInterval self referencing

Hey everyone!

I am looking to recreate this JS in Rescript, but not sure how I can define a setInterval function to later call clearInterval on it’s self.

useEffect(() => {
  let interval = setInterval(() => {
    if (emailField.current) {
      setEmail(emailField.current.value)
      clearInterval(interval)
    }
  }, 100)
})
  type interval
  @val external setInterval: (unit => unit, int) => interval = "setInterval"
  @val external clearInterval: interval => unit = "clearInterval"

  React.useEffect0(() => {
    let interval = Browser.setInterval(() => {
      switch inputRef.current->Js.Nullable.toOption {
      | Some(input) =>
        if input->Browser.getRefValue->Belt.Option.isSome {
          interval->Browser.clearInterval // ERR: The value interval can't be found
        }
      | None => ignore()
      }
    }, 100)

    Some(() => interval->Browser.clearInterval)
  })

Thanks in advance!

(More context on this hack) - How I fixed an issue with a React login form state and Browser autofill

Maybe a mutable let binding will help here?

external asInterval: int => interval = "%identity"

React.useEffect0(() => {
  let interval = ref(asInterval(0))
  interval.contents = Browser.setInterval(() => {
    switch inputRef.current->Js.Nullable.toOption {
    | Some(input) =>
      if input->Browser.getRefValue->Belt.Option.isSome {
        interval.contents->Browser.clearInterval // ERR: The value interval can't be found
      }
    | None => ignore()
    }
  }, 100)
  Some(() => interval.contents->Browser.clearInterval)
})

Not tested, but hopefully shows the idea.

Also, setInterval() and clearInterval() are available in the Js.Global package

2 Likes