'How to calculate forces to be applied to the player on separate createEffect's that resets on each update

I have a counter, that I want to accumulate some numbers by adding to it. On each update it resets to 0. I wanted to separate these updates into separate createEffect. But it doesn't work. How should I change my logic, so the player goes smoothly and stops at the right time. Oh I didn't mention this is for calculating the applied forces on a physics system. So I reset the forces to zero afterwards. So the counter is the result force to be applied.

import { render } from "solid-js/web";
import { on, createSignal, createEffect } from "solid-js";

function Counter() {
  const [update, setUpdate] = createSignal(0);
  const addUpdate = () => setUpdate(update() + 1);

  const [count, setCount] = createSignal(0);

  createEffect(on(update, dt => {
    setCount(0)
  }))

  createEffect(on(update, dt => {
    if (dt % 10 < 3) {
      setCount(_ => _ + 3)
    }
  }))

  createEffect(on(update, dt => {
    if (dt % 10 < 9) {
     setCount(_ => _ + 1)
    }
  }))

// Expected output: `0 4, 1 4, 2 4, 3 1, 4 1, 5 1, 6 1, 7 1, 8 1, 9 1, 10 4, 11 4, 12 4, 13 1`
createEffect(on(update, () => {
  console.log([update(), count()].join(' '))
}))

setInterval(() => {
 addUpdate()
}, 500)

  return (
    <button type="button">
      {count()}
    </button>
  );
}

render(() => <Counter />, document.getElementById("app"));


Solution 1:[1]

It is hard to understand what you are trying to achieve by looking at your code.

The effect runs with every state update. So, you can watch the counter, and clean the interval accordingly.

import { createEffect, createSignal, on } from "solid-js";
import { render } from "solid-js/web";

function Counter() {
  const [count, setCount] = createSignal(0);
  const [collecteds, setCollecteds] = createSignal([]);

  const int = setInterval(() => setCount(c => c + 1), 500);

  createEffect(() => {
    if (count() === 5) {
      clearInterval(int);
    }
  });
  
  // This tracks `count` only, so that you can update
  // collecteds without triggering an infinite loop
  createEffect(on(count, () => {
    setCollecteds([...collecteds(), count()]);
  }));

  return (
    <div>{count()} {JSON.stringify(collecteds())}</div>
  );
}

render(Counter, document.getElementById("app"));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1