I need help creating an efficient JS listener against an array of objects and a video. It works, but is really inefficient and memory intensive, especially if the array of objects is large.
I have a video that is 1 minute long and I want to display objects that are synchronized with this video on the GUI based on timecodes. For example, at 0:23, I want to display a comment.
The synchronized, timecoded objects are stored in an array like this:
comm1 = {text : "I like it", time : 23}
comm2 = {text : "I hate it", time : 48}
comm3 = {text : "I love it", time : 59}
var arr = [comm1, comm2, comm3]
I then have a Flash video player that returns the current playhead position of the video. I can call it through JavaScript like so:
var position = document.getElementById("player").currentTime();
I then created a setInterval object that loops through the array every 250 ms to display the comment like so:
function getCurrentComment(){
for(i=0;i<arr.length;i++){
if(position >= arr[i].time){
getId("comments").innerHTML = arr[i].text;
}
}
}
var commListener = setInterval("getCurrentComment()", 250);
This works visually, but in reality, it continues to execute the “getId(“comments”).innerHTML = arr[i].text” line of code every 250 ms no matter what. Is there better way to do this without having to continuously loop through an array? It gets really bad when there are 100+ objects in the array. I was looking at the Observer Pattern but I don’t think it will work for this since I’m synchronizing in real time with a video.
If you can listen to the seek event, then you can do something like this:
Please note: I did not debug this code, and it might have some issues. I’m just posting it here to give you the general idea…