I have run into what seems like a common problem in svelte but haven't found a good solution. I have a function that is called when a button is pressed in a component, the basic situation is shown below.
<script>
import tick from 'svelte'
let x = 0;
let y = 0;
let z = 0;
async function buttonHandler() {
--- multiple computationally intensive loops
that update the vars x,y,z at different points ---
e.g.
for (a in arr) {
x ++;
await tick();
}
}
</script>
<main>
<button on:click={buttonHandler}>Click Me</button>
<p>{x}</p>
<p>{y}</p>
<p>{z}</p>
</main>
I basically wanted the x, y, z values to update on screen as the function incremented them, to have live updates of the progress. Originally they were not updating until the function completed, and I read that it was because svelte batch updates changes to reactive variables. I then read that the 'tick()' function was designed for this situation, to 'flush' the updates and have the DOM rerender the updated values. However this still isn't working, the only way I can get it work is by replacing tick() with a generic sleep() function:
function sleep(millisec = 0) {
return new Promise((resolve, reject) => {
setTimeout(_ => resolve(), millisec);
});
};
This doesn't seem like its a good solution, and I feel like I must be missing something. Have any others had situations where tick isn't working as expected?