purencool Posted January 14, 2010 Share Posted January 14, 2010 Hi php freaks I have been using prototype in javascript and found that to get setTimeout to call another method I need to add a closure. But I can't get it work can anyone help. I am new to closures. function fadingImagesIn(idArray,intNum){ //this is the constructor for the fading images this.idArray= idArray; this.intNum = intNum; } fadingImagesIn.prototype.fadeIn = function(id) { var element=document.getElementById(id); if (element.timer) window.clearTimeout(element.timer); var startMS = (new Date()).getTime(); element.timer = window.setTimeout("this.changeOpacity('" + id + "',1000," + startMS + ",0,100)",1); } fadingImagesIn.prototype.timer =function(){ var x = this.intNum; x++; alert (this.idArray[0]); for (i=0;i<=x;i++) { if(i == 0){ //Allows page to load setTimeout ( "", 1000 ); }else{ //Makes the images visible. //every second goes to timer and then come back // setTimeout("alert(hi)",1000); setTimeout(function(){this.fadeIn('logoDiv1')},1000); } } } // This creates the object var imagefading = new fadingImagesIn(new Array('logoDiv1','logoDiv2','logoDiv3'), 2); //--> Link to comment https://forums.phpfreaks.com/topic/188408-closure-issue/ Share on other sites More sharing options...
purencool Posted January 14, 2010 Author Share Posted January 14, 2010 Sorry but I forgot to add that the line below is throwing a error, setTimeout(function(){this.fadeIn('logoDiv1')},1000); Error: this.fadeIn is not a function Source File: http://127.0.0.1/public_html/der.php# Line: 84 Link to comment https://forums.phpfreaks.com/topic/188408-closure-issue/#findComment-994662 Share on other sites More sharing options...
salathe Posted January 14, 2010 Share Posted January 14, 2010 As you can see 'this' does not refer to the fadingImagesIn object, resulting in that error. To get the correct scope, you can create a variable referencing the desired 'this' and use that within the anonymous function in setTimeout, like: fadingImagesIn.prototype.timer =function(){ var self = this; // ... setTimeout(function(){self.fadeIn('logoDiv1')},1000); // ... } Link to comment https://forums.phpfreaks.com/topic/188408-closure-issue/#findComment-994755 Share on other sites More sharing options...
purencool Posted January 14, 2010 Author Share Posted January 14, 2010 Thank you that fix that issue Link to comment https://forums.phpfreaks.com/topic/188408-closure-issue/#findComment-995084 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.