www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 23

Thread: sleep() pause() wait()

  1. #1
    Join Date
    Feb 2006
    Location
    Buckingham, UK. (the Town, not the Palace)
    Posts
    148

    sleep() pause() wait()

    Hi,
    'C' has a function sleep() to suspend action for a time.
    Has javaScript any such ability?
    JJ

  2. #2
    Join Date
    Dec 2013
    Posts
    63
    I think that you can't stop processing in javascript, there is no sleep function. Perhaps function setTimeout is what you need (I don't know what exactly you want to achieve).
    E.g.:
    Code:
    setTimeout(function() { alert("Hello World!"); }, 1000);
    Second parameter is the number of milliseconds that the function call should be delayed by. But it doesn't stop execution of the script. During these 1000 milliseconds next lines of your code will be executed.

  3. #3
    Join Date
    Feb 2006
    Location
    Buckingham, UK. (the Town, not the Palace)
    Posts
    148
    Thanks, Blasphemy,
    You're right, setTimeout() will not do the job.
    I'm using JS to position SVG hexagons on a page.
    I'm looking for a sleep function to demonstrate the process.
    This is the sort of code I expect to work. It doesn't.

    var now, prev;
    var delay=1000;
    var dat = new Date();

    now = dat.getTime();
    prev = now + delay;

    do { now = dat.getTime(); }
    while ( now < prev );
    Should I take it sleep is impossible.
    I'm certainly losing sleep!
    Last edited by JimJ; 02-28-2014 at 11:27 AM.

  4. #4
    Join Date
    Dec 2013
    Posts
    63
    Above code doesn't work because 'dat.getTime()' in your loop returns always the same value! Variable 'dat' constains the date and time that was exactly in the moment of calling 'var dat = new Date();' and dat.getTime() doesn't return 'current' time. Try to change
    Code:
    do { now = dat.getTime(); }
    into
    Code:
    do { now = Date.now(); }

  5. #5
    Join Date
    Feb 2006
    Location
    Buckingham, UK. (the Town, not the Palace)
    Posts
    148
    Quote Originally Posted by blasphemy View Post
    Above code doesn't work because 'dat.getTime()' in your loop returns always the same value! Variable 'dat' constains the date and time that was exactly in the moment of calling 'var dat = new Date();' and dat.getTime() doesn't return 'current' time. Try to change
    Code:
    do { now = dat.getTime(); }
    into
    Code:
    do { now = Date.now(); }
    Thanks Blasphemy,
    I tried your suggestions, but to no avail.
    Please don't be offended at my silence, I'm going away for a week.
    If you're at a loose end you might want to nose into my code, html and js.
    I'm not sure I can send 200 odd lines of js.
    If I fail, I might try splitting it.
    Here's the html.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head><title>SHADES.HTML</title>
    <script type="text/javascript" src="shades.js"></script>
    </head>
    <body>
    <script type="text/javascript">
    promt(); start(); defs(); scale(); draw(); end();
    // Globals, arguments and settings in shades.js
    </script>
    </body>
    </html>

  6. #6
    Join Date
    Feb 2006
    Location
    Buckingham, UK. (the Town, not the Palace)
    Posts
    148
    Hi, agaim,
    Here's the JS (or part of it).
    Code:
    // GLOBAL VARIABLES
    var R, G, B;         // Colour of Central Hexagon
    var r, g, b;         // colour of each other hexagon
    var H;               // Height of whole hexagonal Image
    var h, w;            // height,width of individual hexagon
    var y, x;            // Unscaled h/w of individual hexagon
    var C;               // Number of hexagonal 'circles'
    var S;               // stepSize of colourChange
    var W;               // Computed width of Image
    var hx, hy;          // centrePoint of each Hexagon
    var hxh;             // Actual height of individual hexagon
    var fsz;             // Font-size in hexagon labels
    var ms;              // current time in millisecs
    var dat, strt;
    var c   = new Array(3);   // Used in setVals()
    var s   = new Array(3);   // Used in setVals()
    var n   = new Array(3);   // Used in setVals()
    
    var sx  = new Array(6);   // Used in setVals(), then in calcXY() 
    var nx  = new Array(6);   // Used in setVals(), then in calcXY() 
    var sy  = new Array(6);   // Used in setVals(), then in calcXY() 
    var ny  = new Array(6);   // Used in setVals(), then in calcXY() 
    
    s[0]    = new Array(6);   // Used in setVals(), then in calcRGB() 
    s[1]    = new Array(6);   // Used in setVals(), then in calcRGB() 
    s[2]    = new Array(6);   // Used in setVals(), then in calcRGB() 
    n[0]    = new Array(6);   // Used in setVals(), then in calcRGB() 
    n[1]    = new Array(6);   // Used in setVals(), then in calcRGB() 
    n[2]    = new Array(6);   // Used in setVals(), then in calcRGB() 
    
    function prompts()
      {     // Get User's Colour and other requirements
      R=0; r=0; G=0; g=0; B=0; b=0;  // GLOBALS, declared above
    
      R = window.prompt("Red-value (0-255)",215);
      G = window.prompt("Green-value (0-255)",215);
      B = window.prompt("Blue-value (0-255)",215);
    
      H = window.prompt("Suggest ImageHeight (300-900)",468);
      C = window.prompt("Number of Concentric \'Rings\' (1-8)",4);
      S = window.prompt("StepSize of ColourChange (1-9)",5);
      }
    
    function setVals(H,C)
      {
      h = 52;               // nominal height of individual hexagon
      w = 60;               // nominal width  of individual hexagon
      y = H/(2*C+1);        // Unscaled height of individual hexagon
      x = 15*y/13;          // Unscaled width  of individual hexagon
      W = (x*(3*C+2)/2)+1;  // Calculated Width  of Honeycomb image
      H = H*1+1;            // Adjusted Height   of Honeycomb image 
      W = parseInt(W,10);   // Final Calculated Width of Honeycomb
    
      dat = new Date();
      strt= dat.getTime();
    //alert("SETVALS STRT="+strt );
    //alert("SETVALS continue");
    
      r = 0;  g = 0;  b = 0;
      c[0]= 2;  c[1]= -1;  c[2]= -1;
    
      // Used in calcRGB() for adjusting colour shades between neighbours
      s[0][0]= 0; s[0][1]=-1; s[0][2]=-3; s[0][3]=-4; s[0][4]=-3; s[0][5]=-1;
      s[1][0]= 0; s[1][1]= 2; s[1][2]= 3; s[1][3]= 2; s[1][4]= 0; s[1][5]=-1;
      s[2][0]= 0; s[2][1]=-1; s[2][2]= 0; s[2][3]= 2; s[2][4]= 3; s[2][5]= 2;
    
      // Used in calcRGB()
      n[0][0]=-1; n[0][1]=-2; n[0][2]=-1; n[0][3]= 1; n[0][4]= 2; n[0][5]= 1;
      n[1][0]= 2; n[1][1]= 1; n[1][2]=-1; n[1][3]=-2; n[1][4]=-1; n[1][5]= 1;
      n[2][0]=-1; n[2][1]= 1; n[2][2]= 2; n[2][3]= 1; n[2][4]=-1; n[2][5]=-2;
    
      // Used in calcXY()
      sx[0]= 0; sx[1]=45; sx[2]= 45;  sx[3]=  0; sx[4]=-45; sx[5]=-45; 
      nx[0]=45; nx[1]= 0; nx[2]=-45;  nx[3]=-45; nx[4]=  0; nx[5]= 45;
    
      // Used in calcXY()
      sy[0]= 0; sy[1]=26; sy[2]= 78;  sy[3]=104; sy[4]= 78; sy[5]= 26;
      ny[0]=26; ny[1]=52; ny[2]= 26;  ny[3]=-26; ny[4]=-52; ny[5]=-26;
      }
    
    function startSVG(W,H)
      {
      var svg="<svg ";
      document.write(svg.toLowerCase());
      document.writeln('width=\"'+W+'px\"\n height=\"'+H+'px\"\n');
      document.writeln('viewBox=\"0 0 '+W+' '+H+'\"\n version=\"1.1\"\n');
      document.writeln('xmlns=\"http://www.w3.org/2000/svg\"\n');
      document.writeln('xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n');
      }
    
    function defs ( )
      {
      var dfs="<defs>";    var edfs="<\/defs>";
      var grp="<g ";       var egrp="<\/g>";
      var pgn="<polygon ";
      document.writeln(dfs.toLowerCase() + '\n');
      document.writeln(grp.toLowerCase() + 'id="hxg">\n');
      document.write(pgn.toLowerCase());
      document.write(' points="15,-26, 30,0, 15,26, -15,26, -30,0, -15,-26" '); 
      document.writeln(egrp.toLowerCase() + '\n');
      document.writeln(edfs.toLowerCase() + '\n');
      }
    
    function setScale(W,H,C,h)
      {
      var grp="<g ";
      var hit=parseInt(H/2,10);
      var wid=parseInt(W/2,10);
      var numer=H*1000;   var denom=2*C+1;
      var calc=parseInt(numer/denom/h,10);
      var sc=calc/1000;  // Scaling factor to fit 2*C+1 rows into Image-Height
      hxh = y*sc;
      fsz = parseInt(hxh/7,10);
      document.write(grp.toLowerCase());
      document.write(' transform=\"translate(' +wid+ ',' +hit+ ') scale(' +sc+ ')\">');
      
      }
    
    function calcRGB(i,j,k,step)  // based on Globals R, G, B 
      {
      var rv, gv, bv;
      rv = (c[0]*i + s[0][j]*i + n[0][j]*k)*step;
      gv = (c[1]*i + s[1][j]*i + n[1][j]*k)*step;
      bv = (c[2]*i + s[2][j]*i + n[2][j]*k)*step;
      r = R*1 + rv*1;  if(r>255) { r=255; } if(r<0) { r=0; }
      g = G*1 + gv*1;  if(g>255) { g=255; } if(g<0) { g=0; }
      b = B*1 + bv*1;  if(b>255) { b=255; } if(b<0) { b=0; };
      }
    
    function calcXY(i,j,k)
      {
      var sxv, nxv, syv, nyv, hyv;
      sxv=sx[j]*i; nxv=nx[j]*k;
      syv=sy[j]*i; nyv=ny[j]*k; hyv=h*-i;
      hx = ( sxv*1 + nxv*1 );
      hy = ( syv*1 + nyv*1 + hyv*1 );
      }
    
    function labelHex(x,y,rv,gv,bv)
      {
      var rx, ry, gx, gy, bx, by;
      rx=x-8; gx=x-8; bx=x-8; 
      ry=y-8; gy=y*1 +5; by=y*1 +18;
      document.write('  <text x="'+rx+'" y="'+ry+'"  style="font-size: '+fsz+'pt;">'+rv+'<\/text>');
      document.write('  <text x="'+gx+'" y="'+gy+'"  style="font-size: '+fsz+'pt;">'+gv+'<\/text>');
      document.write('  <text x="'+bx+'" y="'+by+'"  style="font-size: '+fsz+'pt;">'+bv+'<\/text>');
      }
    
    function calc(i,j,k,S,idn)
      {      
      var now = 0;
      var prev= 0;
      var delay = 1000;
      var minus = 1393600000000;
      var p_m, n_d, p_s, n_s;
      var nid, nxt;
      var dat, ms;
    
      nid = "n";
      nid += idn;
      nxt = "n";
      idn++;
      nxt += idn;
      prv = "end."+nid; 
    //alert("CALC NID="+nid );
    //alert("CALC NXT="+nxt );
    
      // Calculate the x,y position and the rgb() shade of each hexagon
      calcXY (i,j,k);      // calculate the hx,hy position of hexagon
      calcRGB (i,j,k,S);   // calculate the rgb colour of the hexagon
    
      document.write   ('<use xlink:href="#hxg" x="'+hx+'" y="'+hy+'" ');
      document.writeln ('  id="nxt" style="fill: rgb('+r+','+g+','+b+');" />');
      document.writeln ('  <animateTransform attributeName="transform" ');
      document.writeln (' animateType="XML" type="rotate" ');
      document.writeln (' from "0 '+hx+' '+hy+'" to "60 '+hx+' '+hy+'" ');
      document.writeln (' begin=prv dur="1s" fill="freeze" />');
      document.writeln (' </use> ');
    
    //  labelHex(hx,hy,r,g,b);   // Label the hexagon with its R,G,B values
    
    //  dat = new Date();
    //  now = dat.getTime();
    
    //  prev = now + delay;
    //  do     { now = dat.getTime(); }
    //  while  ( now < prev );   
      }
    
    function drawHex(W,H,C,S)
      {
      var i, j, k;    // Loop counters
      var idn = 0;
      var later, delay=1000;
      var dat = new Date();
      var strt = dat.getTime();
      var now  = dat.getTime();
      var l_s, n_s;
    
      document.write  ('<use xlink:href="#hxg"  x="0" y="0" ');
      document.writeln('  style="fill: rgb('+R+','+G+','+B+');" /> ');
    //  labelHex(0,0,R,G,B);  // Label the Central Hexagon
    
      for ( i=1 ; i<=C ; i++ )       // Count the 'Rings' in the Honeycomb
        {
        for ( j=0 ; j<6 ; j++ )      // Count the 6 Sectors of the Hexagon
          {
          for ( k=0 ; k<i ; k++ )    // Count the Segments within the Sector
            {
            idn++;
            calc (i,j,k,S,idn);
    
    //  later = now + delay;    // some future millisec
    //  do  { now = Date.now(); }
    //  while ( now < later );   
            }
          }
        }
      }
    
    function end()
      {
      var egrp="<\/g>";  var esvg="<\/svg>";
      document.writeln(egrp.toLowerCase() + "\n");
      document.writeln(esvg.toLowerCase() + "\n");
      }
    
    function promt()
      {
      prompts(); 
      setVals(H,C);
      }
    
    function start()  { startSVG(W,H); }
    function scale()  { setScale(W,H,C,h); }
    function draw()   { drawHex(W,H,C,S); }
    Last edited by jedaisoul; 03-18-2014 at 04:30 PM.

  7. #7
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,407
    What do you want to achieve by these functions?

    IMHO wait, sleep and pause will all be doing the same thing, causing the execution of code to be suspended for 'x' seconds.

    My thoughs are the following would do.

    Code:
    var n = new Date();
    var e = n.getTime() +1000;
    while( e <= n.getTime() );
    Will suspend all program activity until e >= the time + 1 second, the variable can be re written to accomodate a functrion that when passed with the number of seconds, it will wait that amount of time, eg.

    Code:
    function sleep(s){
        if(!s) return;
        var n = new Date();
        var e = n.getTime() + (s*1000);
        while( e <= n.getTime() );
    }
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  8. #8
    Join Date
    Dec 2013
    Posts
    63
    Quote Originally Posted by \\.\ View Post
    My thoughs are the following would do.

    Code:
    var n = new Date();
    var e = n.getTime() +1000;
    while( e <= n.getTime() );
    I think this code will not work.

    Calling 'new Date()' creates Date object containing current date and time, that is date and time that was exactly in the moment of calling this code. Method getTime() returns the number of milliseconds between midnight of January 1, 1970 and the specified date (and time). So 'n.getTime()' will return the number of milliseconds between midnight of January 1, 1970 and the date (and time) that was exactly in the moment of calling 'var n = new Date()'. It means that 'n.getTime()' in your loop condition will always return the same value, and this value will be always lower than value of 'e'.

  9. #9
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,407
    Quote Originally Posted by blasphemy View Post
    I think this code will not work.

    Calling 'new Date()' creates Date object containing current date and time, that is date and time that was exactly in the moment of calling this code. Method getTime() returns the number of milliseconds between midnight of January 1, 1970 and the specified date (and time). So 'n.getTime()' will return the number of milliseconds between midnight of January 1, 1970 and the date (and time) that was exactly in the moment of calling 'var n = new Date()'. It means that 'n.getTime()' in your loop condition will always return the same value, and this value will be always lower than value of 'e'.
    I haven't tested this idea, it was just a simple suggestion and your thinking is not correct, if the changes made to the function are done to correct any issues, then this is the theory.

    1. call a function which will take a parameter for seconds
    2. get a time reference x.getTime() for the start
    3. get a future time reference which is 's' x 1000 to make the reference milliseconds and add it to a time reference of x.getTime() + future time
    4. use a loop to test for this future time expiring and if it has passed, stop looping.
    5. function ends.

    It matters not that the time reference is based on time since 1 Jan 1970, your looking to see if that time ref + the sleep time has expired by getting a new time reference.

    Any code errors are up to the person looking to use such an idea to sort out and iron out any operational problems.

    So if your x.getTime() sets a variable y with a time reference of 1393716581131 and then the value of (s * 1000) is added to it and stored to y, you have a loop using a fresh date object, eg while( y<= new Date().getTime() ){}; to loop until time has passed, eg y will have a time reference of 1393716586131 if a 5 second pause is needed.

    I can see one possible issue, Google Chrome... it does not play ball with some routines.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  10. #10
    Join Date
    Mar 2009
    Posts
    511
    Using a "while" loop for delaying the program is not a good idea. If the cumulative delays are sufficiently long the browser user will get an "unresponsive script" message, which I doubt is wanted here.

    One thing you can do is to use setTimeout at the very end of the function and have it call the next function in the sequence. For example, lets say we have three functions and we want a three second delay between them.

    Code:
    //!!!!!!!!! change this
    function first(){
        //some code here
    }
    function second(){
        // other code here
    }
    function third(){
        // still other code here
    }
    
    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! --make it
    function first(){
        //some code here
        setTimeout(second, 3000);
    }
    function second(){
        // other code here
        setTimeout(third, 3000);
    }
    function third(){  // UNCHANGED
        // still other code here
    }
    
    //start program
    first();

  11. #11
    Join Date
    Feb 2006
    Location
    Buckingham, UK. (the Town, not the Palace)
    Posts
    148
    Thanks, Tcobb,
    I'm not using multiple functions.
    I'm simply trying to slow down a loop.
    It builds a 'honeycomb' of simple coloured hexagons.
    Am I simply accumulating a bunch of setTimeouts?
    Thanks for your advice.
    JJ

  12. #12
    Join Date
    Mar 2009
    Posts
    511
    The same principles apply when you want a "loop" with a delay--you don't actually do a loop. Paste and run--

    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    <script>
    // creating elements with a loop--no delay
    function fastLoop(limit){
        var i, p;
        for(i = 0; i < limit; i++){
    	//guts
    	p = document.createElement('p');
    	document.body.appendChild(p);
    	p.innerHTML = "paragraph: " + i;
    	//end of guts
        }
    }
    
    //this accomplishes the same thing with a delay
    function timeGap(i,limit){
        var p, fn;
        //guts
        p = document.createElement('p');
        document.body.appendChild(p);
        p.innerHTML = "paragraph: " + i;
        //end of guts
        i++;
        if(i < limit){  //has the limit been reached?
    	fn = function(){  
    	    timeGap(i, limit);
    	}
    	setTimeout(fn, 3000);  //setTimeout to call itself
        }
    }
    
    window.onload = function(){
        timeGap(0,5);
    }
    </script>
    </head>
    <body>
    </body>
    </html>
    There are many ways to do this, but this illustrates the general principle.

  13. #13
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,407
    You say (TCobb) that using a while loop is not best but you use a for loop which is no better.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  14. #14
    Join Date
    Mar 2009
    Posts
    511
    You say (TCobb) that using a while loop is not best but you use a for loop which is no better.
    If you look at the code its not a loop at all. It essentially uses itself as a callback function with a control variable so that it quits calling itself when the task is completed. The for loop in the code quoted is not ever invoked, it is used to illustrate how to do its equivalent with a time delay.

  15. #15
    Join Date
    Feb 2006
    Location
    Buckingham, UK. (the Town, not the Palace)
    Posts
    148
    Hi Tcobb,
    I like your code.
    Tested it, both fast and slow.
    You prove your point.
    I've got to learn to code like you.

    (by the way)
    I have an eccentric way of coding,
    (so that open and close braces are stacked).

    When I edited your code for my benefit in reading,
    I found you have a redundant close-brace on line 32

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles