最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - setTimeout calling function inside function - Scope-Issue - Stack Overflow

programmeradmin4浏览0评论

So, the problem is that I have a function inside a function that needs to be called by setTimeout. That doesn't work however because setTimeout will assume that the function it calls has the root as its' scope.

Any idea how I could solve this without changing the scope of the function?

Edit:

Here is what I mean:

function general(){
    function saysomething(){
        console.log('hi there');
    }
setTimeout("saysomething();", 1000);
}

The setTimeout fails..

So, the problem is that I have a function inside a function that needs to be called by setTimeout. That doesn't work however because setTimeout will assume that the function it calls has the root as its' scope.

Any idea how I could solve this without changing the scope of the function?

Edit:

Here is what I mean:

function general(){
    function saysomething(){
        console.log('hi there');
    }
setTimeout("saysomething();", 1000);
}

The setTimeout fails..

Share Improve this question edited Nov 18, 2011 at 18:30 Julian asked Nov 18, 2011 at 18:15 JulianJulian 3121 gold badge2 silver badges14 bronze badges 2
  • 1 What? Provide example code or clarify what are you asking about. – WTK Commented Nov 18, 2011 at 18:20
  • First argument of setTimeout requires you to specify a function object, not string. – iankit Commented Nov 7, 2014 at 9:44
Add a ment  | 

2 Answers 2

Reset to default 10
function general(){
    function saysomething(){
        console.log('hi there');
    }
    setTimeout(saysomething, 1000);
}

Not positive this is what you mean but you can pass the variables when you call the function in the setTimeout

function f1(){
    var a='1';
    var b='b';
    setTimeout(function(){f2(a,b);},1000)

}

function f2(a,b){
      alert(a + b);
}

f1();
发布评论

评论列表(0)

  1. 暂无评论