Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error "Cannot read property of undefined" when wrapped in a setTimeout [duplicate]

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?

like image 287
Kayboy Bebop Avatar asked Dec 14 '16 06:12

Kayboy Bebop


1 Answers

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);
like image 196
Suren Srapyan Avatar answered Nov 14 '22 22:11

Suren Srapyan