Go Back   CodingForums.com > :: Client side development > JavaScript programming > Post a JavaScript

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 06-24-2012, 11:32 PM   PM User | #16
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,454
Thanks: 0
Thanked 498 Times in 490 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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/
felgall is offline   Reply With Quote
Old 06-25-2012, 11:06 AM   PM User | #17
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,454
Thanks: 0
Thanked 498 Times in 490 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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/
felgall is offline   Reply With Quote
Old 06-25-2012, 07:24 PM   PM User | #18
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,460
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
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 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%
rnd me is offline   Reply With Quote
Old 06-25-2012, 09:58 PM   PM User | #19
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,454
Thanks: 0
Thanked 498 Times in 490 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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/
felgall is offline   Reply With Quote
Old 06-25-2012, 11:13 PM   PM User | #20
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,460
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
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!
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%

Last edited by rnd me; 06-25-2012 at 11:16 PM..
rnd me is offline   Reply With Quote
Old 06-25-2012, 11:39 PM   PM User | #21
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,454
Thanks: 0
Thanked 498 Times in 490 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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);
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 06-26-2012 at 12:00 AM..
felgall is offline   Reply With Quote
Old 06-26-2012, 12:59 AM   PM User | #22
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,460
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
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; }
}
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%

Last edited by rnd me; 06-26-2012 at 01:04 AM..
rnd me is offline   Reply With Quote
Old 06-26-2012, 03:19 AM   PM User | #23
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,454
Thanks: 0
Thanked 498 Times in 490 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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?
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 06-26-2012 at 03:21 AM..
felgall is offline   Reply With Quote
Old 06-26-2012, 11:28 AM   PM User | #24
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,454
Thanks: 0
Thanked 498 Times in 490 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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/
felgall is offline   Reply With Quote
Old 06-26-2012, 07:05 PM   PM User | #25
nicholagi
New to the CF scene

 
Join Date: Jun 2012
Posts: 8
Thanks: 0
Thanked 0 Times in 0 Posts
nicholagi is an unknown quantity at this point
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());
nicholagi is offline   Reply With Quote
Old 06-26-2012, 08:07 PM   PM User | #26
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,037
Thanks: 197
Thanked 2,411 Times in 2,389 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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.
Philip M is offline   Reply With Quote
Old 06-26-2012, 10:02 PM   PM User | #27
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,454
Thanks: 0
Thanked 498 Times in 490 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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/
felgall is offline   Reply With Quote
Old 06-26-2012, 11:08 PM   PM User | #28
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,460
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
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...
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%

Last edited by rnd me; 06-26-2012 at 11:13 PM..
rnd me is offline   Reply With Quote
Old 06-26-2012, 11:29 PM   PM User | #29
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,454
Thanks: 0
Thanked 498 Times in 490 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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/
felgall is offline   Reply With Quote
Old 07-01-2012, 10:08 PM   PM User | #30
c1lonewolf
Regular Coder

 
Join Date: Sep 2002
Posts: 216
Thanks: 0
Thanked 11 Times in 11 Posts
c1lonewolf is an unknown quantity at this point
my two cents:
javascript sleep/pause
__________________
NO Limits!!
c1lonewolf is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 10:38 PM.


Advertisement
Log in to turn off these ads.