setTimeout calling function inside function - Scope-Issue

依然范特西╮ 提交于 2019-12-11 03:14:27

问题


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..


回答1:


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



回答2:


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();


来源:https://stackoverflow.com/questions/8187038/settimeout-calling-function-inside-function-scope-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!