www.webdeveloper.com
Results 1 to 3 of 3

Thread: delay the execution of a function

  1. #1
    Join Date
    Nov 2013
    Posts
    44

    delay the execution of a function

    say i have a function toDo();
    i want to call the function whenever i scrolled the window.
    and i want to begin the execution effect after a sudden period of time using setTimeout() function.so what could be the correct code.
    i think
    window.onScroll=setTimeout(toDo,1000);
    is it the correct form ,or there are other cleaner and safer way to do so???

  2. #2
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    The way you have it now will only execute the toDo function once, and you don't even need to scroll for it to execute:

    window.onScroll=setTimeout(toDo,1000);

    You will need to attach a function to that event for it to fire properly:

    Code:
    function toDo()
    {
    	alert('Done!');
    }
    
    window.onscroll = function()
    {
    	setTimeout(toDo, 1000);
    };
    Unless this is not a problem for you, every single fire of that event will create a new delayed call to toDo.
    If you wish to only have toDo called once the onscroll event has stopped firing and after the delay, you can do:

    Code:
    function toDo()
    {
    	alert('Done!');
    }
    
    window.onscroll = (function()
    {
    	var id;
    	return function()
    	{
    		if (id) {clearTimeout(id);}
    		id = setTimeout(toDo, 1000);
    	};
    }());
    It looks more complicated, but it keeps the global scope clean-er.
    JavaScript: Learn | Validate | Compact | bionoid

  3. #3
    Join Date
    Nov 2013
    Posts
    44
    thanks a lot!!

Thread Information

Users Browsing this Thread

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

Tags for this Thread

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