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.
Results 1 to 10 of 10
  1. #1
    Regular Coder
    Join Date
    Jul 2007
    Location
    Velsen Noord, Netherlands
    Posts
    218
    Thanks
    6
    Thanked 0 Times in 0 Posts

    timeout inside function

    I would like to know (maybe I know the answer already), but can a function be paused, like halfway the function pause the function for lets say for 5 seconds, then continue.

    Thanks

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,081
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Javascript has no "sleep" function, but sometimes you can split your function in two and call the second part after a delay using setTimeout().

    Code:
    <script type = "text/javascript">
    
    function one() {
    alert ("Hello");
    setTimeout(two,5000);  // 5 seconds delay
    }
    
    function two() {
    alert ("World");
    }
    
    one();
    
    </script>

    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.

  • #3
    Regular Coder
    Join Date
    Jul 2007
    Location
    Velsen Noord, Netherlands
    Posts
    218
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    Javascript has no "sleep" function, but sometimes you can split your function in two and call the second part after a delay using setTimeout().

    Code:
    <script type = "text/javascript">
    
    function one() {
    alert ("Hello");
    setTimeout(two,5000);  // 5 seconds delay
    }
    
    function two() {
    alert ("World");
    }
    
    one();
    
    </script>
    That´s an idea, but I have no idea how I can do this on the code below:
    Code:
    function activateBox(divId) {
    //alert('start activate '+divId +'   activebox = '+activeBoxId );
     
    		$('#workspace').children('div').each(function () {
    	
    	//alert('unset all for '+$(this).attr('id'));
    			$(this).get(0).contentEditable = false;
    			$(this).draggable("destroy");
    			$(this).resizable("destroy");
    			$(this).droppable("destroy");
    			$(this).css("outline","1px solid silver");
    			$("#delete_box").css("display","none");
    			editorInfo('pagina Nr.: '+(activePage+1)+' geen van de boxen zijn actief, dubbel click op een box om te activeren');
    	//alert('all unset');
    		}); // all unset now set new box	
    		activeBoxId = '';
    		if ( divId != 'workspace') {
    //alert('now activateBox  box '+divId +'   activebox = '+activeBoxId );
    			var type = divId.substr(0,3);
    			activeBoxId = divId;
    			$("#"+divId).css("outline","3px dotted red");
    			var styleForm = getStyle("#"+divId,'FORM');	
    			$("#styleFormDiv").html( styleForm ); 
    			$("#styleFormLabel").html("Styles "+divId);
    			$("#styleFormLabel").css("display","block");
    			$("#delete_box").css("display","block");
    //alert('type = '+type+" |  now  if statement TXT or else IMG || ei_id");
    			if (type == 'TXT') { 
    				//alert(' now check if Lorem '+$(divId).html().substr(0,5));
    				if ( $("#"+divId).html().substr(0,5) == 'Lorem' ) { $("#"+divId).html('');}
    				makeDivDragResize("#"+divId , "TXT"); 
    				editorInfo('Pagina Nr.:'+(activePage+1)+'  Box : '+activeBoxId+' is actief click op box om te text te wijzigen');
    			} else {
    	//alert(' divId = '+divId+ '  html = '+$("#"+divId).html());
    				if (divId.substr(0,5) == 'ei_id' ) {
    					// its a image not empty container after resize drag replace image save img id.
    					tmpStoreImageId = divId.substr(6); // needed to put image back after resize or drag OR loose focus
    					divId  = $("#"+divId).parent().attr('id'); // continue with parent box
    	//alert(' nu parent id dus is  divId = '+divId);
    	
    
    					$("#"+divId).css("outline","3px dotted red");
    					var styleForm = getStyle("#"+divId,'FORM');	
    					$("#styleFormDiv").html( styleForm ); 
    					$("#styleFormLabel").html("Styles "+divId);
    					$("#styleFormLabel").css("display","block");
    					$("#delete_box").css("display","block");
    			
    					$("#"+divId).css("outline","3px dotted red");
    					if ( divId.substr(0,3) == 'IMG'  && tmpStoreImageId != 0 ){ 
    						activeBoxId=divId;
    						editImageId = tmpStoreImageId;
    	//alert('activate Box  activeBoxId = '+activeBoxId+ 'editImageId = '+ editImageId +' tmpStoreImageId '+ tmpStoreImageId);
    						activateImageEditor("#"+divId);  
    					}
    					
    					$("#"+divId).html(' verplaats of hervorm de afbeelding box dan wordt afbeelding weer herplaatst met nieuwe afmetingen OF <button id="cancelImageButton" onClick="restoreImage();">Annuleer </button>');
    				}
    				makeDivDragResize("#"+divId , 'IMG');
    				editorInfo('Pagina Nr.:'+(activePage+1)+'  Image Box : '+activeBoxId+' is actief. <button id="showImgInfo" onClick="showHideImgInfo();">Edit Afbeelding</button>');
    //alert('all done activate image'+activePage+'  Image Box : '+activeBoxId)
    			}
    		}
    		if (activeBoxId != '' ) { $(".delete_box_icon").css("display","block");}
    //alert('activate done for  '+divId);
    }
    The code highlighted is the code that should have a 5 sec delay, because this code is being used in another function (the other function can't delay).

    Any suggestions?

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,081
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Javascript has no "sleep" function, but sometimes you can split your function in two and call the second part after a delay using setTimeout().

    Your code does not lend itself to this.

    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.

  • #5
    Regular Coder
    Join Date
    Apr 2005
    Location
    Texas
    Posts
    448
    Thanks
    24
    Thanked 63 Times in 63 Posts
    I would say you might consider a different pattern for your code that allows you to watch for certain events and when circumstances align you can run the necessary code. The observer pattern comes to mind.

    But in the mean time maybe this could bridge the gap:
    Code:
    /*This is the code we want to wait to evaluate until just the right values exist*/
    codeToEvaluate = function (){
    editorInfo('Pagina Nr.:'+(activePage+1)+'  Image Box : '+activeBoxId+' is actief. <button id="showImgInfo" onClick="showHideImgInfo();">Edit Afbeelding</button>');
    //alert('all done activate image'+activePage+'  Image Box : '+activeBoxId)
    }
    
    waitTillReady  = function (){
        var testVal ,
            resolvedVal ,
            codeToEvaluate;
    
        var CheckIfReady = function () {
                if (testVal != resolvedVal) setTimeOut(CheckIfReady() , 500);
                codeToEvaluate;
            } ,
            init = function (args) {
                waitTillReady.testVal = args[0];
                waitTillReady.resolvedVal = args[1];
                waitTillReady.codeToEvaluate = args[2];
                CheckIfReady();
            };
    
        return {
            'testVal' : testVal ,
            'resolvedVal' : resolvedVal ,
            'codeToEvaluate' : codeToEvaluate ,
            'init' : init
        }
    }();
    
    function activateBox(divId) {
    //alert('start activate '+divId +'   activebox = '+activeBoxId );
     
    		$('#workspace').children('div').each(function () {
    	
    	//alert('unset all for '+$(this).attr('id'));
    			$(this).get(0).contentEditable = false;
    			$(this).draggable("destroy");
    			$(this).resizable("destroy");
    			$(this).droppable("destroy");
    			$(this).css("outline","1px solid silver");
    			$("#delete_box").css("display","none");
    			editorInfo('pagina Nr.: '+(activePage+1)+' geen van de boxen zijn actief, dubbel click op een box om te activeren');
    	//alert('all unset');
    		}); // all unset now set new box	
    		activeBoxId = '';
    		if ( divId != 'workspace') {
    //alert('now activateBox  box '+divId +'   activebox = '+activeBoxId );
    			var type = divId.substr(0,3);
    			activeBoxId = divId;
    			$("#"+divId).css("outline","3px dotted red");
    			var styleForm = getStyle("#"+divId,'FORM');	
    			$("#styleFormDiv").html( styleForm ); 
    			$("#styleFormLabel").html("Styles "+divId);
    			$("#styleFormLabel").css("display","block");
    			$("#delete_box").css("display","block");
    //alert('type = '+type+" |  now  if statement TXT or else IMG || ei_id");
    			if (type == 'TXT') { 
    				//alert(' now check if Lorem '+$(divId).html().substr(0,5));
    				if ( $("#"+divId).html().substr(0,5) == 'Lorem' ) { $("#"+divId).html('');}
    				makeDivDragResize("#"+divId , "TXT"); 
    				editorInfo('Pagina Nr.:'+(activePage+1)+'  Box : '+activeBoxId+' is actief click op box om te text te wijzigen');
    			} else {
    	//alert(' divId = '+divId+ '  html = '+$("#"+divId).html());
    				if (divId.substr(0,5) == 'ei_id' ) {
    					// its a image not empty container after resize drag replace image save img id.
    					tmpStoreImageId = divId.substr(6); // needed to put image back after resize or drag OR loose focus
    					divId  = $("#"+divId).parent().attr('id'); // continue with parent box
    	//alert(' nu parent id dus is  divId = '+divId);
    	
    
    					$("#"+divId).css("outline","3px dotted red");
    					var styleForm = getStyle("#"+divId,'FORM');	
    					$("#styleFormDiv").html( styleForm ); 
    					$("#styleFormLabel").html("Styles "+divId);
    					$("#styleFormLabel").css("display","block");
    					$("#delete_box").css("display","block");
    			
    					$("#"+divId).css("outline","3px dotted red");
    					if ( divId.substr(0,3) == 'IMG'  && tmpStoreImageId != 0 ){ 
    						activeBoxId=divId;
    						editImageId = tmpStoreImageId;
    	//alert('activate Box  activeBoxId = '+activeBoxId+ 'editImageId = '+ editImageId +' tmpStoreImageId '+ tmpStoreImageId);
    						activateImageEditor("#"+divId);  
    					}
    					
    					$("#"+divId).html(' verplaats of hervorm de afbeelding box dan wordt afbeelding weer herplaatst met nieuwe afmetingen OF <button id="cancelImageButton" onClick="restoreImage();">Annuleer </button>');
    				}
    				makeDivDragResize("#"+divId , 'IMG');
    				waitTillReady.init([val1 , val2 , codeToEvaluate]);
    			}
    		}
    		if (activeBoxId != '' ) { $(".delete_box_icon").css("display","block");}
    //alert('activate done for  '+divId);
    }
    sorry, I fell asleep trying to debug that last night, so I don't think the waitTillReady() is quite finished, and now I must be on my way... but what I was getting at is you want to initialize a loop with setTimeout, test the values that you are waiting for and when they are what you want you can execute your code... I'll come back and run it later when I have a moment, but you can always try to experiment with a similar model...
    Allwisend bin ich nicht, doch viel ist mir bewursst
    -Goethe

  • #6
    Regular Coder
    Join Date
    Jul 2007
    Location
    Velsen Noord, Netherlands
    Posts
    218
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Thanks blaze4218 for the reply, the only thing is, I don't use any 'value'.

    What happens an image is inside a div box, and when I double click this div box, the image is 'exported' to an image editor (webbased). The editorInfo line at the beginning of your code, is the part that holds a button to go to the editor.

    When I run the original code, double click the div box and then the edit button, the image is not loaded correct. But when I double click and wait for 5 second, then click the edit button, the image is loaded correct. So what I want is that users don't have to count till 5 themselfs before continue.

    I hope I explained it well.

    Thanks again.

  • #7
    Regular Coder
    Join Date
    Apr 2005
    Location
    Texas
    Posts
    448
    Thanks
    24
    Thanked 63 Times in 63 Posts
    Your image editor should still have some value that you can monitor that would let you know if you image has been returned. Or you could monitor the image container to see if the image has finished loading, either way: wouldn't you rather know that your script will work every time instead of setting a 5 count and hoping for the best? what if a larger image is used, will your script fail? (or maybe somehow recover...)

    Anyway, I finished the concept from last night to observe some value inside of a loop and execute the code when it resolves to true. This can be modified to see if an image has loaded (see comments) which would help your script if I get what your doing...

    Code:
    
    <button id="getReady">Load My Image</button>
    <div id="imageContainer">image1</div>
    
    <script>
    
    /*here is our code to eval*/
    var codeToEvaluate = function(){alert('my image has returned!')}
    
    waitTillReady  = function (){
        var testVal ,
            resolvedVal ,
            codeToEvaluate;
    
        var CheckIfReady = function () {
                if (eval(testVal) != resolvedVal) {
                    var Loop = setTimeout(CheckIfReady , 1000);
                    return
                }
                codeToEvaluate();
            } ,
            init = function (args) {
                testVal = args[0];
                resolvedVal = args[1];
                codeToEvaluate = args[2];
                CheckIfReady();
            };
    
        return {
            'testVal' : testVal ,
            'resolvedVal' : resolvedVal ,
            'codeToEvaluate' : codeToEvaluate ,
            'init' : init
        }
    }();
    
    /*
    *  This is where we send the testVal as a string. I'm sure there is 
    *  another way to pass the variable pointer besides using eval, but 
    *  I don't know it... also we reference the value we would like it to equal
    *  and the code to evaluate. another example of this line would be:
    *  waitTillReady.init(['document.getElementById(\'image\').onload' , 'true' , codeToEvaluate])
    *  which might actually help in your case...
    */
    waitTillReady.init(['document.getElementById(\'imageContainer\').innerText' , 'image2' , codeToEvaluate])
    
    document.getElementById('getReady').onclick = function (){
        document.getElementById('imageContainer').innerText = 'image2';
    }
    
    </script>
    Allwisend bin ich nicht, doch viel ist mir bewursst
    -Goethe

  • #8
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,081
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Disable the edit button until five seconds after the div has been clicked?
    Last edited by Philip M; 02-21-2012 at 05:30 PM.

    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.

  • #9
    Regular Coder
    Join Date
    Apr 2005
    Location
    Texas
    Posts
    448
    Thanks
    24
    Thanked 63 Times in 63 Posts
    just found this snippit on testing image load (which is the direction I hope your headed in), hope it helps
    Quote Originally Posted by felgall View Post
    There are plenty of browsers out there that don't support image.onload at all so that code wont work there either. The only cross browser method I have found to test if an image is loaded is to test if the width or height of the image is greater than zero. If you set width and height in the HTML then you need to take a copy of the image and test that instead.
    Allwisend bin ich nicht, doch viel ist mir bewursst
    -Goethe

  • #10
    Regular Coder
    Join Date
    Apr 2005
    Location
    Texas
    Posts
    448
    Thanks
    24
    Thanked 63 Times in 63 Posts
    Is that what his code was supposed to do? *disable* the button?

    well, no I suppose you would disable the button and then run waitTillReady.init() wherein the "codeToExecute()" would contain the necessary script to re-enable the button... you really just use that function to wait until something happens, then do something, it can be configured to monitor any var and test it against a value...
    Allwisend bin ich nicht, doch viel ist mir bewursst
    -Goethe


  •  

    Posting Permissions

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