1
function f1()
{
  c = setTimeout(f2,200);
}
function f2()
{
 //code
}

The above code is just fine. But what I want to ask that: can I use some argument in function f2() which is passed from the calling environment? That is:

 function f1(v1)
    {
      c = setTimeout(f2(v1),200);
    }
    function f2(v2)
    {
     //code
    }

Is it valid? Because I tried something like this,but the problem is that I am not able to clearTimeout by using variable c. I am not sure what to do.

Parveez Ahmed
  • 1,325
  • 4
  • 17
  • 28

3 Answers3

1

Use Closure -

function f1(v1)
{
    c = setTimeout(f2(v1), 200);
}

function f2(v2)
{
     return function () {
         // use v2 here, and put the rest of your
         // callback code here.
     }
}

This way you will be able to pass as many arguments as you want.

Since you are declaring c as a global variable (which is bad), you can easily clear the timeout using -

clearTimeout(c);

If you are still not being able to clear the timeout, it only means that the duration has elapsed and your callback fired, or there is some error somewhere else. In that case, post your code that you are using to clear your timeout.

MD Sayem Ahmed
  • 28,628
  • 27
  • 111
  • 178
  • thnks @sayem,,,,it just works fine!!! I will be glad to know from you why declaring c as a global variable is bad? – Parveez Ahmed Sep 01 '13 at 14:09
  • 1
    @rosemary: Because when you declare a global variable, you clutter the global namespace i.e., any other variable with the same name gets over-written. Similarly, you can accidentally overwrite other useful global variables. For detailed explanation, please [see this](http://stackoverflow.com/questions/4246284/why-are-globals-bad). – MD Sayem Ahmed Sep 01 '13 at 14:59
0
var timeout;
// Call `f2` with all arguments that was passed to the `f1`
function f1 () {
  var args = arguments;
  timeout = setTimeout(function () { f2.apply(this, args) }, 200);
}

Or in this way:

// Call `f2` with some params from `f1`
function f1 (v1) {
  timeout = setTimeout(function () { f2(v1) }, 200);
}

Answer to your question: you couldn't clear the timeout because you execute function immediately.

Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55
0

You can either use the function.bind method or you can simply wrap the invocation

function f1(v1) { 
    c = setTimeout(function() {
        f2(v1);
    }, 200); 
} 
Woody
  • 7,578
  • 2
  • 21
  • 25