简体   繁体   English

setInterval()对象的方法调用

[英]setInterval() object's method call

I try to call an object method within a setInterval() timer, but without success. 我尝试在setInterval()计时器中调用对象方法,但未成功。 The method gets called once when creating the Object is created. 创建对象时,该方法将被调用一次。 Changes in the method declaration only gave me errors that update isn't a function at all. 方法声明中的更改仅给我带来错误,即更新根本不是功能。

Is this a problem of function accessibility or did i make a general structure mistake? 这是函数可访问性的问题还是我犯了一般的结构错误?

  window.viz = new VizOne("test.json"); setInterval(viz.updateViz(), 5000); //one object for each viz, each has a setup and an update method function VizOne(dataFile){ var file = dataFile; var data = []; var s = Snap(500,100); var fullLength = 0; var allRects = []; $.getJSON(file, function( rawData ) { var i = 0; $.each( rawData, function( key, val ) { data[i] = val; i++; }) }).done(function() { for(i = 0; i<data.length;i++){ allRects.push(s.rect(fullLength, 0, data[i],100) .attr({fill: "#bada55", opacity: Math.random()}) ); console.log("x: "+ fullLength +", value: "+ data[i]); fullLength= fullLength+parseInt(data[i]); } }); //method this.updateViz = function() { $.getJSON(file, function( rawData ) { var i = 0; $.each( rawData, function( key, val ) { data[i] = val; i++; }) }).done(function() { console.log("update vizOne") for(i = 0; i<allRects.length; i++){ allRects[i].animate({opacity: Math.random()},3000); } }) } }; 

The first argument to setInterval needs to be a function . setInterval的第一个参数必须是一个函数

You are calling viz.updateViz() and passing the return value (which is undefined). 您正在调用 viz.updateViz()并传递返回值 (未定义)。

Since updateViz depends on being called in the right context (it uses this internally), you need to create a new function that will call it in the right context. 由于updateViz依赖于在正确的上下文中被调用(它this内部使用this ),因此您需要创建一个新的函数来在正确的上下文中调用它。

setInterval(viz.updateViz.bind(viz), 5000);

Using () after a method name will call the method immediately and the return value of the method call will be passed as an argument to setInterval . 在方法名称后使用()将立即调用该方法,并且该方法调用的返回值将作为参数传递给setInterval Get rid of the () and just pass the function reference. 摆脱() ,只传递函数引用。

setInterval(viz.updateViz(), 5000); is calling the result of viz.updateViz() , but you would like instead write setInterval(viz.updateViz, 5000); 正在调用viz.updateViz()的结果,但是您想写setInterval(viz.updateViz, 5000);

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

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