简体   繁体   English

setInterval中全局变量的范围

[英]Scope of global variable inside setInterval

function data(){
    var dataval = anyValue;
    var myVar = setInterval(function(){computeData()});
    function computeData(){
      //inside this function there will be computations 
      //where dataval is included
    }
 }

This is just an example. 这只是一个例子。 My problem is that when I update the value of dataval and call the data(), the value is not updated inside the setInterval function. 我的问题是,当我更新dataval的值并调用data()时,该值不会在setInterval函数内部更新。 Unless I change the value again and call data(). 除非我再次更改值并调用data()。 But that is not even working well. 但这甚至不能很好地工作。

anyValue  = 10

//the computation works //计算工作

//if i update it to decreasingly, anyValue = 9, //it still uses the value 10, //如果我将其更新为递减值,则anyValue = 9,//它仍使用值10,

//then if i use anyValue = 8, now it uses the value 9 //然后如果我使用anyValue = 8,则现在使用值9

This is not the code I am using. 这不是我正在使用的代码。 But same logic. 但是逻辑相同。 Thanks! 谢谢! I hope you get my question! 希望你能回答我的问题! ` `

将您的计算数据函数computeData(object) data()之外,并使其接受变量,例如computeData(object)然后将所需的对象通过var myVar = setInterval(function(){computeData(dataval)});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM