Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #39113

Re: boolean while loops "how to stop" and "make room for textout to textarea"

Newsgroups comp.lang.javascript
Date 2020-11-03 14:08 -0800
References <6d2d33cc-9b19-469c-a25c-d8d2f862f0aco@googlegroups.com> <e804ad67-46e2-4c43-a1f4-bb90dcf1d127n@googlegroups.com>
Message-ID <a5d50dcd-dcfd-4c4a-8848-e70b72f4375bo@googlegroups.com> (permalink)
Subject Re: boolean while loops "how to stop" and "make room for textout to textarea"
From Jonas Thörnvall <jonas.thornvall@gmail.com>

Show all headers | View raw


Den tisdag 3 november 2020 kl. 22:28:02 UTC+1 skrev sc...@sauyet.com:
> Jonas Thörnvall wrote:
> 
> > When creating a while loop like this. 
> > while(run==true){ 
> > 
> > } 
> 
> Unless that block of code itself updates the value of `run`, this will
> continue to run indefinitely, assuming `run` starts as `true`.
> 
> As others have pointed out, browsers run their code in a single thread
> unless you've invoked WebWorkers or some such.
> 
> And this means that there is no external mechanism to interrupt this
> infinite loop.
> 
> 
>  
> > 1. How can i stop it, i tried a button that call function that set 
> > run=false but that do not work. 
> 
> The trouble is that there is no way for your code to stop and allow
> the browser to handle your button press.  You've essentially told the
> browser to continue this process until it's complete and then move on
> to the next event in the event loop.  But since this one doesn't stop
> the event loop never reaches that event.
> 
> What people are trying to tell you with `setTimeout`, `setInterval`,
> or `requestAnimationFrame` is that you can keep your code processing,
> but to do so you need to divide it into manageable chunks that will
> be posted one-by-one to the event loop.  Here I discuss only 
> `setTimeout`.  The others are similar.
> 
> The model is simply one of running
> 
>     const processChunk = (...args) => {
> 	  // Do some work with the arguments.
>       // Decide whether there is more to do. (This might include
> 	  //   testing whether `run` has been set.)
>       if (moreToDo) {
> 	    setTimeout (processChunk, 0, ...newArgs)
>       }
> 	}
> 
> So, for your coin-flipping streak-checker, we would want to check
> some number of flips -- let's say a million -- then in a `setTimeout`
> call, call back to the current function with whatever state is
> necessary to keep going.  Or you could keep this in some higher scope,
> even global.  My solution below uses a combination of an outer 
> function scope and paramters.
> 
> Between these calls, the JS engine can check if there is anything else
> in the event queue and run that before coming back to the next chunk.
> And this is what keeps the process running smoothly.
> 
> There is an art, not a science, to knowing how big a chunk to create.
> If you created a new task for every coin flip, the overhead of the
> function calls and the `setTimeout` mechanism itself will overwhelm
> the time spent in actual work.  But if your chunks involved a billion
> coin flips, the browser will start to lag because these chunks simply
> take too long to process.
> 
> In the code below, I set `batchSize` to one million (`1e6`), and find
> that for my simple console-based ui, this is fast enough, but ten 
> million (`1e7`) starts to feel laggy.  It might be different if you
> have serious DOM manipulations involved, but I can't imagine anything
> below `1e5` would be necessary.
> 
> 
> 
> > 2. How can i write out values to textarea while still in loop, it 
> > does not seem "to have time" want to do it until loop breaks?
> 
> There are various ways to achieve this.  The naive one is to just
> incorporate the IO / DOM manipulation inside your loop.  A more
> structured version of this would be to register a listener to your
> system and call back to that listener when there are changes of note.
> Because that call is happening in the same task, it will process
> alongside your calculations.  This is what I do below.
> 
> 
> ----------
> 
> Here is an example of such a counter to track streaks of heads or 
> tails, using `Math.random` to generate a sequence of pseudo-random
> numbers.
> 
> I have a working version posted online at 
> 
>     <https://codepen.io/CrossEye/pen/ZEORrXo?editors=0012>
> 	
> 
> First, the code for the counter:
> 
> 
> ```
> const flipCounter = () => {
>   let batchSize = 1e6, running = false, total = 0, listeners = []
>   
>   const flip = () => Math.random() < .5 ? 'heads' : 'tails'
>   
>   const run = ({type, streaks = [], current = 0}) => {
>     for (let i = 0; i < batchSize; i++) {
>       if (flip() === type) {
>         current += 1
>       } else {
>         if (current > (streaks[streaks.length - 1] || 0)) {
>           streaks .push (current)
>           listeners.forEach(fn => fn({streaks, flips: total + i}))
>         }
>         current = 0
>       }
>     }
>     total += batchSize
>     if (running) {setTimeout(run, 0, {type, streaks, current})}   
>   }
>   
>   return {
>     start: (type) => {running = true; total = 0; run ({type})},
>     totalFlips: () => total,
>     listen: (listener) => {listeners .push (listener); return true},
>     stop: () => {running = false}
>   }
> }
> ```
> 
> And now the code that uses it:
> 
> 
> ```
> const counter = flipCounter();
> counter .listen (
>   ({flips, streaks}) => 
>     console.log(`After ${flips} flips, streaks are [${streaks}]`)
> )
> setTimeout(() => {
>   counter .stop (); 
>   console .log (`Total flips: ${counter.totalFlips()}`)
> }, 10000)
> counter.start('heads') 
> ```
> 
> 
> 
> You'll note that I don't try to build your user interface.  That's
> not really relevant to the questions raised.  Instead we create a
> counter with `counter = flipCounter()`.  We register a listener
> that does nothing more than `console.log` the data supplied to it.  In
> your UI, you would presumably update the controls with the new data.
> 
> We use `setTimeout` to simulate someone pressing the "stop" button ten
> seconds from now, also logging the number of total flips tried in that
> time.
> 
> And finally, we start the counter running with the choice of "heads".
> 
> Presumably there are paralells you could create with your UI.
> 
> 
> A typical session might look something like this:
> 
> 
> ```
> After 1 flips, streaks are [1]
> After 10 flips, streaks are [1,3]
> After 51 flips, streaks are [1,3,4]
> After 131 flips, streaks are [1,3,4,5]
> After 274 flips, streaks are [1,3,4,5,6]
> After 515 flips, streaks are [1,3,4,5,6,9]
> After 1660 flips, streaks are [1,3,4,5,6,9,10]
> After 3761 flips, streaks are [1,3,4,5,6,9,10,23]
> After 3743891 flips, streaks are [1,3,4,5,6,9,10,23,24]
> After 55330189 flips, streaks are [1,3,4,5,6,9,10,23,24,31]
> Total flips: 330000000
> ```
> 
> ----------
> 
> Finally, could we stop with the attitude?  People here are interested
> in discussing Javascript and other ES implementations.  They may love
> it or hate it, but they are here because somehow or another JS is
> useful to them.
> 
> There are no issues discussing the downsides of the language.
> Certainly there are plenty of them.  But your incessant whining about
> how poorly designed it is, and how it simply doesn't compare to 
> language X doesn't add anything.  You often mention Basic.  I don't
> know if you are talking about old line-number basic from 40+ years ago
> or Visual Basic or VB.NET, but I have used the first two, and I have
> to say this problem would be no simpler in either of those, which were
> also single-threaded.
> 
> But the detailed explanation I just gave might have come your way
> earlier if you asked polite questions rather than railed against the
> language and against those trying to help you with it.
> 
> And, you've been told often, learn to make proper USENET posts.  A
> proper newsreader is a help, but if you're stuck with Google Groups,
> put in the effor to format your answer carefully, trim your quotations
> properly, and make it more enjoyable to interact with you.
> 
>   -- Scott

I was mor interested in something that did continous updates, for example every second.It is something backward with javascript you really want the pooling going out from loop. Not have a rendition "setTimeout setInterval" that call a coin flipping function every xth function.

But you are correct you could chunk it up, but i did not see the point when the calls to coinflipping anywhere near realtime.

Instead the interface set the length of loop, and all other grahical UI is done after loop exit.

https://jonasth.github.io/random.html

Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

boolean while loops "how to stop" and  "make room for textout to textarea" Jonas Thörnvall <jonas.thornvall@gmail.com> - 2020-10-31 03:44 -0700
  Re: boolean while loops "how to stop" and  "make room for textout to textarea" Jonas Thörnvall <jonas.thornvall@gmail.com> - 2020-10-31 04:20 -0700
    Re: boolean while loops "how to stop" and  "make room for textout to textarea" Julio Di Egidio <julio@diegidio.name> - 2020-10-31 06:07 -0700
      Re: boolean while loops "how to stop" and  "make room for textout to textarea" Jonas Thörnvall <jonas.thornvall@gmail.com> - 2020-10-31 09:41 -0700
      Re: boolean while loops "how to stop" and  "make room for textout to textarea" Jonas Thörnvall <jonas.thornvall@gmail.com> - 2020-10-31 09:45 -0700
      Re: boolean while loops "how to stop" and  "make room for textout to textarea" Jonas Thörnvall <jonas.thornvall@gmail.com> - 2020-10-31 09:48 -0700
        Re: boolean while loops "how to stop" and  "make room for textout to textarea" Julio Di Egidio <julio@diegidio.name> - 2020-10-31 10:10 -0700
          Re: boolean while loops "how to stop" and  "make room for textout to textarea" Jonas Thörnvall <jonas.thornvall@gmail.com> - 2020-10-31 10:42 -0700
      Re: boolean while loops "how to stop" and  "make room for textout to textarea" Jonas Thörnvall <jonas.thornvall@gmail.com> - 2020-10-31 10:05 -0700
        Re: boolean while loops "how to stop" and "make room for textout to textarea" Arno Welzel <usenet@arnowelzel.de> - 2020-10-31 18:49 +0100
          Re: boolean while loops "how to stop" and "make room for textout to textarea" Jonas Thörnvall <jonas.thornvall@gmail.com> - 2020-10-31 11:07 -0700
            Re: boolean while loops "how to stop" and "make room for textout to textarea" John G Harris <niam@jghnorth.org.uk.invalid> - 2020-11-01 11:39 +0000
            Re: boolean while loops "how to stop" and "make room for textout to textarea" Arno Welzel <usenet@arnowelzel.de> - 2020-11-01 13:52 +0100
      Re: boolean while loops "how to stop" and  "make room for textout to textarea" Julio Di Egidio <julio@diegidio.name> - 2020-11-01 21:57 -0800
        Re: boolean while loops "how to stop" and  "make room for textout to textarea" Jonas Thörnvall <jonas.thornvall@gmail.com> - 2020-11-01 23:44 -0800
  Re: boolean while loops "how to stop" and "make room for textout to textarea" Arno Welzel <usenet@arnowelzel.de> - 2020-10-31 18:24 +0100
    Re: boolean while loops "how to stop" and "make room for textout to textarea" Jonas Thörnvall <jonas.thornvall@gmail.com> - 2020-10-31 10:44 -0700
      Re: boolean while loops "how to stop" and "make room for textout to textarea" Arno Welzel <usenet@arnowelzel.de> - 2020-10-31 18:52 +0100
        Re: boolean while loops "how to stop" and "make room for textout to textarea" Jonas Thörnvall <jonas.thornvall@gmail.com> - 2020-10-31 11:14 -0700
          Re: boolean while loops "how to stop" and "make room for textout to textarea" John G Harris <niam@jghnorth.org.uk.invalid> - 2020-11-01 11:45 +0000
            Re: boolean while loops "how to stop" and "make room for textout to textarea" Arno Welzel <usenet@arnowelzel.de> - 2020-11-01 14:02 +0100
              Re: boolean while loops "how to stop" and "make room for textout to textarea" John G Harris <niam@jghnorth.org.uk.invalid> - 2020-11-01 17:38 +0000
                Re: boolean while loops "how to stop" and "make room for textout to textarea" Arno Welzel <usenet@arnowelzel.de> - 2020-11-01 21:07 +0100
                Re: boolean while loops "how to stop" and "make room for textout to textarea" John G Harris <niam@jghnorth.org.uk.invalid> - 2020-11-02 19:36 +0000
                Re: boolean while loops "how to stop" and "make room for textout to textarea" Arno Welzel <usenet@arnowelzel.de> - 2020-11-03 18:34 +0100
                Re: boolean while loops "how to stop" and "make room for textout to textarea" Julio Di Egidio <julio@diegidio.name> - 2020-11-03 11:48 -0800
                Re: boolean while loops "how to stop" and "make room for textout to textarea" Arno Welzel <usenet@arnowelzel.de> - 2020-11-04 15:17 +0100
                Re: boolean while loops "how to stop" and "make room for textout to textarea" Arno Welzel <usenet@arnowelzel.de> - 2020-11-04 15:18 +0100
                Re: boolean while loops "how to stop" and "make room for textout to textarea" Julio Di Egidio <julio@diegidio.name> - 2020-11-04 12:52 -0800
                Re: boolean while loops "how to stop" and "make room for textout to textarea" Arno Welzel <usenet@arnowelzel.de> - 2020-11-05 16:12 +0100
          Re: boolean while loops "how to stop" and "make room for textout to textarea" Arno Welzel <usenet@arnowelzel.de> - 2020-11-01 14:02 +0100
  Re: boolean while loops "how to stop" and "make room for textout to textarea" "sc...@sauyet.com" <scott@sauyet.com> - 2020-11-03 13:27 -0800
    Re: boolean while loops "how to stop" and "make room for textout to textarea" Jonas Thörnvall <jonas.thornvall@gmail.com> - 2020-11-03 14:08 -0800
      Re: boolean while loops "how to stop" and "make room for textout to textarea" Scott Sauyet <scott.sauyet@gmail.com> - 2020-11-03 17:28 -0800

csiph-web