简体   繁体   中英

setInterval() object's method call

I try to call an object method within a setInterval() timer, but without success. 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 .

You are calling viz.updateViz() and passing the return value (which is undefined).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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