# Dynamic with side-effects

I'm working on a UI where I want to display many images, too many to have in memory at once. So I'm trying to implement a "paging" system to display a handful of images at a time and only load on demand. I've come up with something that kind of produces the result I want, but the problem is that it basically pegs the processor. I'm hoping someone can help me spot what I'm missing. This simplified version of the code is enough to hit the processor pretty hard (and continuously)

(*Warning: This may lock up your notebook*)
Import["someimage.jpg"];
page]
SlideView[Dynamic[LoadPage[#]] & /@ Table[i, {i, 1, 20}],
ImageSize -> Automatic]


My expectation is that because nothing is changing (except for when the slide is changed) that Import should be run once per slide, but it is apparently being run continuously (as evidenced by opening task manager and watching CPU utilization / notebook locking up). Can anyone explain what I'm missing and help me get the CPU utilization under control?

• Keeping answers accepted you discourage new visitors as this basically says 'issue solved'. So is it? – Kuba Apr 26 '17 at 6:24
• I understand, I just thought it would be unfair to Mike to move the goal posts. StackExchange failure on my part :( – Dan Apr 26 '17 at 6:27
• I wasn't focusing on content, that was a general note. If Maik answer doesn't fit your new goals but fit the old one you should really accept it and ask another question with clear description of the problem. – Kuba Apr 26 '17 at 6:48
• I think that a) I've messed this all up, but b) both excessive CPU and excessive memory usage fall under Dynamic with side-effects so I will undo the acceptance for now (with apologies). And accept an answer for sure tomorrow (come what may). I'll also do a better job next time I ask a question. Sorry again. – Dan Apr 26 '17 at 6:57

Try this instead and let me know if it helps:

SlideView[
Dynamic[Refresh[LoadPage[#], None]] & /@ Table[i, {i, 1, 20}],
ImageSize -> Automatic]


You can readily see the difference between using Refresh and not by adding a Print to your Module:

LoadPage[page_] := Module[{i = 0},
Print[page];
Import["image.jpg"];
page];

• That did it. Sorry, I even read the Advanced Dynamic doc but didn't realize this was the fix. I know I should technically post another question for this, but if I may sneak one addendum in. I mentioned tangentially that I'm really paging through many images. Now that the CPU issue is gone I see it never frees the memory for each image. Any ideas in that direction? – Dan Apr 26 '17 at 5:14
• Can you expand your question with some real world examples and show how you are monitoring memory usage? – Mike Honeychurch Apr 26 '17 at 5:45
• Ok, sorry I was trying a few things to see if I could figure it out (mentioned in the edit). I really appreciate your help. – Dan Apr 26 '17 at 6:13