Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 2 of 2 FirstFirst 12
Results 16 to 30 of 30
  1. #16
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by DrDOS View Post
    Actually there is a way to implement a blocking type 'sleep' in javascript, it's rather crude and rude from the user standpoint, but it will do the job if needed. Just put up an alert which says 'Please click OK after three seconds.
    The problem with that is that the built in alert box is intended for debugging and so displays options for turning off JavaScript or turning off alerts.

    I actually developed this sleep function as a half way stage to being able to replace the built in alert with your own custom alerts with the addition of one line of code per function containing alerts.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  2. #17
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by rnd me View Post
    Code:
    Function.prototype.Name=function(){return String(this).split("(")[0].split(" ")[1]};
    That doesn't work.

    String(this).split("(")[0] returns function but when you add the .split(" ")[1] it returns undefined.

    The name of the variable that the function is assigned to doesn't appear anywhere in the String(this) to retrieve it.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  3. #18
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,346
    Thanks
    11
    Thanked 589 Times in 570 Posts
    Quote Originally Posted by felgall View Post
    That doesn't work.

    String(this).split("(")[0] returns function but when you add the .split(" ")[1] it returns undefined.

    The name of the variable that the function is assigned to doesn't appear anywhere in the String(this) to retrieve it.
    then the function has no name (not all do). can you post a named function example for which the code does not work?
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  4. #19
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by rnd me View Post
    then the function has no name (not all do). can you post a named function example for which the code does not work?
    The syntax I used for creating the functions in the first post in this thread always works when used anywhere in the code - it just means that you can't easily get the name of the function and so end up with it being specified twice in the extra statement that does this conversion. This is trivial compared to all the issues that could be caused by defining the functions the other way.

    The alternate way of creating functions where the word function comes before the name has all sorts of limitations where it can cause conflicts or may not even work at all. I therefore recommend for people to not use that format. There was a post here recently where someone wanted to redefine a function part way through their code and had issues because they used the wrong format to define the function (wrong in the sense that the format they used overwrote the first function with the second before the first was called instead of overwriting it after).
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  5. #20
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,346
    Thanks
    11
    Thanked 589 Times in 570 Posts
    Quote Originally Posted by felgall View Post
    The alternate way of creating functions where the word function comes before the name has all sorts of limitations where it can cause conflicts or may not even work at all. I therefore recommend for people to not use that format. .
    ok i understand. you are passing out bad advice.

    All functions should have a name, even function expressions. Since strict mode eliminates arguments.callee, the internal function name is the only way to "get the function name from within a function method". In fact the internal function name is the only way for a strict function to refer to itself at all, for recursion or whatever.

    just because you use a function name doesn't mean that you can't assign a function to a variable under a different local name. Personally, i like the way js hoists names to local lexical scope, but i can see how conditional function definitions can be confusing to code when relying on that behavior.

    If you need to re-define a method i strongly recommend defining the function as a local variable expression first thing. This lets you clobber the name (re-defining the function) mid-stream. Still, you should give that function an internal name. Even if you don't need self-reference or recursion, the function name appears on the stack and in firebug, making debugging much easier.


    for example,
    Code:
    sleep = function(t,f) {
    would be better written as
    Code:
     sleep = function _sleep(t,f) {

    in conclusion, every function deserves a name!
    Last edited by rnd me; 06-25-2012 at 11:16 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  6. #21
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by rnd me View Post

    for example,
    Code:
    sleep = function(t,f) {
    would be better written as
    Code:
     sleep = function _sleep(t,f) {
    I can sort of see your point but thast would still only apply in those limited situations where JavaScript allows you to define named functions.

    How would you rewrite the following three functions where the first function only needs to exist until it finishes running the first time and the other two are defined inside an if statement where JavaScript does not allow you to define named functions?

    Code:
    addEvent = function(ob, type, fn) {
    if (window.addEventListener)
      addEvent = function(ob, type, fn ) {
        ob.addEventListener(type, fn, false );
      };
      else if (document.attachEvent)
        addEvent = function(ob, type, fn ) {
          var eProp = type + fn;
          ob['e'+eProp] = fn;
          ob[eProp] = function(){ob['e'+eProp]( window.event );};
          ob.attachEvent( 'on'+type, o[eProp]);
        };
      else return; 
    addEvent(ob, type, fn):
    };
     
    addEvent(document.getElementById('myid'),
      'click',
      myfunction);
    Last edited by felgall; 06-26-2012 at 12:00 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  7. #22
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,346
    Thanks
    11
    Thanked 589 Times in 570 Posts
    Quote Originally Posted by felgall View Post
    I can sort of see your point but thast would still only apply in those limited situations where JavaScript allows you to define named functions.

    How would you rewrite the following three functions where the first function only needs to exist until it finishes running the first time and the other two are defined inside an if statement where JavaScript does not allow you to define named functions?

    Code:
    addEvent = function(ob, type, fn) {
    if (window.addEventListener)
      addEvent = function(ob, type, fn ) {
        ob.addEventListener(type, fn, false );
      };
      else if (document.attachEvent)
        addEvent = function(ob, type, fn ) {
          var eProp = type + fn;
          ob['e'+eProp] = fn;
          ob[eProp] = function(){ob['e'+eProp]( window.event );};
          ob.attachEvent( 'on'+type, o[eProp]);
        };
      else return; 
    addEvent(ob, type, fn):
    };
     
    addEvent(document.getElementById('myid'),
      'click',
      myfunction);



    there's nothing stopping you from naming those function expressions.
    that said, i don't think that code even works. where is "o" defined? ...


    to answer the question, you don't need a wrapper at all. in fact, that's just extra run-time function overhead and event-time closure overhead.

    like i said before, just use function expressions first-thing:

    Code:
    var addEvent = function _addEventW3(ob, type, fn) {
        ob.addEventListener(type, fn, false );
    };
    
    if(document.attachEvent){
        addEvent = function _addEventIE(ob, type, fn ) {
          ob.attachEvent( 'on'+type, function(){ return fn.call(ob, window.event )} );
        };
    } else {
     if(! window.addEventListener){
        addEvent = function _addEventDOM0(ob, type, fn ) {
          ob["on"+ type] = fn;
        };
      }//end if !ael?
    }
    after that, addEvent() is the correct function for w3, ie or dom0 browsers, and firebug tells you which version of addEvent you are using if any exceptions come up.


    unsolicited bonus: my addEvent :
    Code:
    function addEvent( obj, type, fn ) {
    	var ename=  type.replace(/^on/i,"");
    	var resp = obj.attachEvent 	? 
    		 obj.attachEvent( "on" + ename, function(){ return fn.call(obj, window.event )}  ) : 
    		obj.addEventListener(ename, fn, false );
    	if(!resp){ obj["on"+ename] = fn; }
    }
    Last edited by rnd me; 06-26-2012 at 01:04 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  8. #23
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by rnd me View Post
    there's nothing stopping you from naming those function expressions.
    I see where I have been getting confused with this - I was comparing function expressions with function declarations and hadn't realised that you can still name the function used in a function expression by adding a name so that it looks like a function declaration but still works as a function expression. I had thought that adding the name after the function converts it to a declaration rather than the presence of the = in front converting a declaration to an expression.

    Thanks also for pointing out the typo on the page where I have that code posted as an example of how to lazy load functions.

    Now I understand what you are getting at about naming all functions.

    Presumably anonymous functions used as namespace wrappers to keep scripts separated would be an exception?
    Last edited by felgall; 06-26-2012 at 03:21 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  9. #24
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by rnd me View Post
    can you post a named function example for which the code does not work?
    I can now answer this question. The answer is that it wouldn't work for ANY named function if the browser is Safari 2 - that browser does not include the name when you convert a named function into a String.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  10. #25
    New to the CF scene
    Join Date
    Jun 2012
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts
    sleep() in JavaScript

    PHP has a sleep() function, but JavaScript doesn't. Well, this is because it's useless, you might say, and you'll be right. But for simulating heavy processing and for misc performance measurements, it could be useful. So here's how you can go about creating a sleep() in JavaScript.
    The code

    function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
    break;
    }
    }
    }

    Usage

    Sleep for 1 second (1000 milliseconds):

    console.log(new Date());
    console.log('Dude!');
    sleep(1000);
    console.log(new Date());

  11. #26
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,015
    Thanks
    203
    Thanked 2,538 Times in 2,516 Posts
    Quote Originally Posted by nicholagi View Post
    sleep() in JavaScript
    That is in effect the same code as I posted in Post #4.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  12. #27
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by nicholagi View Post
    So here's how you can go about creating a sleep() in JavaScript.
    That is the same code Philip already posted and it doesn't sleep - it hogs the entire CPU for the specified time so as to not allow the person to use their computer during that time - unless the time exceeds the browser limit for how long it will allow a script to run for in which case part way through the person would see a popup allowing them to kill the script completely.

    Posting code that is the same as has already been posted contributes nothing to the discussion.

    A true sleep function stops running the current script until the end of the sleep period and then starts running it again at that time - zero CPU usage during the sleep period not 100% CPU usage. The only way to do that in JavaScript is using setTimeout and the script I posted to start this thread demonstrates a way that you can get the JavaScript to rewrite itself to incorporate the setTimeouts for you in certain limited situations - ie. that you are not trying to insert a sleep into a loop and that there is nothing else to run after the current function. Where those limitations do not apply the only way to incoprporate a sleep into JavaScript is to manually rewrite the code to incorporate the setTimeout calls.

    On my page http://www.felgall.com/jstip114.htm I outline the sort of manual rewrite required to incorporate the setTimeouts into a loop inside a function. That stuill assumes that there is nothing else that would run immediately after the function.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  13. #28
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,346
    Thanks
    11
    Thanked 589 Times in 570 Posts

    one working solution

    Quote Originally Posted by felgall View Post
    A true sleep function stops running the current script until the end of the sleep period and then starts running it again at that time - zero CPU usage during the sleep period not 100% CPU usage.
    i got you covered in FF and chrome, ALMOST in IE. if there's a way to robotic-ally close the window in IE i'm missing, please share.


    Code:
    function sleep(duration) {
    	var URL = "data:text/html,"+encodeURIComponent("<html><head><title>sleeping</title></head><body><h1>zzz</h1>\
    	<script>setTimeout(function(){window.returnValue=+new Date; window.close();}, "+duration+");</script></body></html>");
    	var resp = window.showModalDialog(URL, null, " resizable: no; center: on; dialogwidth: 300; dialogheight: 120; dialogtop:10; dialogleft: 10");
    	return resp;
    }

    Code:
    //DEMO
    
    [
     +new Date,
     sleep(7654),
     +new Date
    ]
    returns:
    Code:
    FF: [1340748461240, 1340748470832, 1340748470923]
    CH: [1340748169454, undefined,     1340748177134]
    there is lag on it, so take that into consideration. chrome has much less pop-up delay, so it's closer.
    but for a coding project (not a public site), it does stall at 0% CPU for >= duration as advertised...
    Last edited by rnd me; 06-26-2012 at 11:13 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  14. #29
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,640
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by rnd me View Post
    i got you covered in FF and chrome, ALMOST in IE.
    That looks like an interesting alternative - particularly if you were creating a custom alert replacement rather than a sleep function as then your IE problem is resolved.

    Unfortunately Opera doesn't support showModalDialog which is why I started out looking at ways to achieve the effect without using that call.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  15. #30
    Regular Coder
    Join Date
    Sep 2002
    Posts
    456
    Thanks
    0
    Thanked 20 Times in 20 Posts
    my two cents:
    javascript sleep/pause
    NO Limits!! DHCreationStation.com
    ------------------------------------------------------------
    Broken items wanted for tinkerin'! PostItNow@BrokenEquipment.com
    Global Complaint Dept.


 
Page 2 of 2 FirstFirst 12

Posting Permissions

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