Wednesday, 20 April 2016

javascript - Error "Cannot read property of undefined" when wrapped in a setTimeout




I have been working on a piece of code that is meant to handle multiple, small video elements on a single webpage but I am having trouble making the multiple progress bars sync with their respective videos.




(Current jsFiddle prototype)



This piece of code $(this).find("progress").attr("value", $("video", this)[0].currentTime); seems to work inside the main function, but when I wrap it in another function with a setTimeout so the progress bar actually animates I get this error:




"Cannot read property 'currentTime' of undefined at function"




I've tried a few variations to see if I could get it working myself but I haven't been able to fix it by throwing code at the wall like I usually do.




Would someone be able to tell me why it's doing this?


Answer



In the setTimeout your this is not the main this. So your code doesn't work. To work in the setTimeout, you need to get the this before the setTimeout and the use it.



Example



var that = this;
setTimeout(function(){
// here use that
},100);


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...