jacobdo
jacobdo

Reputation: 1615

Avoid UI freeze during a computationally heavy call

I have the following event listener

button.addEventListener('click', function(){
 this.classList.add('disabled');
 aFunctionThatTakesLongToExecute();
});

The problem is that the repaint on the screen associated with the newly added class for the button takes place on when the execution of aFunctionThatTakesLongToExecute is completed and that creates a stutter-y user experience.

Is there a way to force a repaint even while the javascript function is executing?

Upvotes: 2

Views: 234

Answers (1)

Seblor
Seblor

Reputation: 7136

I don't really understand the behavior you're describing, but you can wrap your function call like this :

setTimeout(aFunctionThatTakesLongToExecute);

Basically, it calls your method asynchronously and immediatly, as setTimeout second parameter is not set (usually it is the time before execution in milliseconds).

Keep in mind that this syntax works if aFunctionThatTakesLongToExecute does not take any parameters. Else, you have to wrap the function call in another (anonymous) function and give that new function to the setTimeout instruction like this :

setTimeout(() => {
    aFunctionThatTakesLongToExecute(yourParameter);
});

Here's a link to the doc : https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

Upvotes: 1

Related Questions