3
$\begingroup$

I have a function which takes relatively long to compute.

longtask[str_String] := (Pause[0.5]; ToUpperCase[str])

I need to show the result of this function "live" as applied to an input dynamically typed into a text box. I need typing to be fluid and fast. I expect the output to follow with some lag.

Here's an example:

DynamicModule[{str = ""},
 Deploy@Column[{
    InputField[Dynamic[str], String, FieldSize -> {30, 2}, ContinuousAction -> True],
    Dynamic[
     longtask[str],
     SynchronousUpdating -> False]
    }
   ]
 ]

The problem: Sometimes the character that I just typed gets immediately deleted. Why? How can I prevent this?

To test this, just quickly type any sentence into the text box. For example, if I type "Once upon a time there was a little girl.", I get something like this:

enter image description here

If you watch carefully while typing, you will notice that all characters appear, but some of them get immediately removed.

Is there a way to prevent this without affecting the responsiveness of the input field?


To put it differently: I am dealing with slow evaluations in Dynamic. I want ContinuousUpdating -> True. I understand that the output will respond slowly to the input, but I do not want this to affect the performance of the input. Is this technically possible?

Part of the reason why I want ContinuousUpdating -> True is that an InputField won't update otherwise until it loses focus.

$\endgroup$
  • $\begingroup$ @Kuba I didn't realize that. I can actually do that. $\endgroup$ – Szabolcs Nov 18 '16 at 12:25
3
$\begingroup$

My guess it is a problem with FE-Kernel synchornization of variables state (str copy is here and there).

Notice that str which is not a DynamicModule's variable works well. Quite often it is not a major problem. Last value won't be preserved across sessions but at least it can be properly initialized in Initialization.

One needs to pick a less conflict prone name e.g. MyPackage`Gui`specificname but the code itself doesn't have to be changed:

With[{str := MyPackage`Gui`whatever}, 
 DynamicModule[{}, 
  Deploy@Column[{InputField[Dynamic[str], String, 
      FieldSize -> {30, 2}, ContinuousAction -> True], 
     Dynamic[longtask[str], SynchronousUpdating -> False]}], 
  Initialization :> (str = "")]
 ]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.