How to detect change in youtube getCurrentTime()? - javascript

Is there are any way to detect the change of time in getCurrentTime() of YouTube API?
Purpose:To play single video for limited time(<1 min) in my page and move on to next video.
I was thinking to use object.watch but it only works for the variables not the functions.
I also try to bind something in the original source code https://s.ytimg.com/yts/jsbin/www-widgetapi-vfl9twtxR.js but it was too complicated.

Because the YouTube player is wrapped in an iFrame, you are dependent on what the player exposes, and while they've exposed the current time via the getCurrentTime() function, they haven't exposed any events raised whenever the time might get updated (in fact, the time is only updated to the exposed function 6 or 7 times per second, and it isn't always consistent).
So your only option is to set up a javascript timer. Lots of ways to do that; a simple one would be like this:
setInterval(function(){
// here you'd raise some sort of event based on the value of getCurrentTime();
},100); // polling 8 times a second, to make sure you get it every time it changes.
As the postMessage from the iFrame isn't always perfectly consistent, you could have this interval timer be greater. Or you could use something like requestAnimationFrame to poll 60 times a second.

The first example at
https://developers.google.com/youtube/iframe_api_reference#Getting_Started
gives you almost completely exactly what you need to get started. The code there is starting a timer once the video starts then waits 6 seconds to stop the video. What you'd want to do instead of stopping the video after 6 seconds is to fire a new YT.Player instance on the same div after 60 seconds.

Related

Qualtrics & Javascript Precise Timer Using Time Spend on a Page

I am doing research with an experiment using qualtrics and unfortunately I am completely new to coding. In my experiment a block of questions should be ended after a certain time (in this case 50 seconds). So far I have been using a solution (which I found here: https://research-it.wharton.upenn.edu/uncategorized/qualtrics-loop-merge-tips/) that appeared rather neat using a blank embedded variable "test_time", display logic and the following javascript code which I copied to every page of the block:
Qualtrics.SurveyEngine.addOnload(function()
{
var elapsed = Date.now() - Number("${e://Field/test_time}");
if (elapsed >= 50000){
Qualtrics.SurveyEngine.setEmbeddedData("test_time", 0);
}
});
However, in the exported data when summing up information from timing questions that I included, I see that people have extremely varying time they actually can spend on the questions of the block (from 30 to almost 50 seconds). I am guessing this is due to the fact that the script uses the time of the clock, irrespective of lag caused by a bad internet connection or slow browser.
However, for my project it is important that people actually have the same time for the task. I suspect I could use the information of the timing questions, but somehow I can't access them in Javascript. Another idea is to record the difference between the page appearing and the click on the next button.
I appreciated any of your ideas and inputs!
Use the built-in embedded variable Q_TotalDuration, which is the elapsed survey time in seconds. Set the start time of the block in the survey flow just before the block:
startBlock = ${e://Field/Q_TotalDuration}
Then your JavaScript becomes:
var elapsed = parseInt("${e://Field/Q_TotalDuration}") - parseInt("${e://Field/startBlock}");
if(elapsed >= 50) {
//do something here
}
I don't understand what happens when the time limit is reached and time_test is set to zero in your original code. It wouldn't have any impact on the current page. It seems like you should be setting up a timeout function to click the Next button when the time threshold is reached.

Javascript - hide div 1 sec before live stream on video ends

I have this in page:
<video src="blob://some-live-stream" autoplay></video>
<div id="hideMePlease"> hide 1 sec before video ends</div>
I would like to hide the div 1 sec before the video ends, how can i do?
N.B: i can't know video duration, it's a live stream , and the video autostops so i have no way to stop it myself.
If, as you state, you cannot know the length of the video because it's streaming, it will be impossible (relativistic time travel notwithstanding) for you to schedule an event one second before it finishes.
However, I would at least first try to use the duration property of the video, it may be that metadata is made available as part of the stream early on. If it is, you can use that to schedule the hiding of your div.
As an aside, if you visit the page http://www.w3.org/2010/05/video/mediaevents.html, you'll find that the duration is set correctly as soon as you start playing the video, despite the fact it seems to be streaming from either an MP4, OGG or WEBM file). So it's at least possible, though it may depend on the data stream itself (whether the metadata comes before or after the actual video data).
If the data is not available (I think you get Inf for the duration in that case), then you're just going to have to hide the div at the earliest possible time after that.
That would presumably be when it finishes (fires the onended event).
So, in short, if you can get the duration (or periodically get the time remaining which might be better), use that. Otherwise fall back to hiding it at the end and start hassling w3c to provide the functionality you want in HTML6.

Chrome setInterval crashes at 10000 ms

I'm working on a Javascript stopwatch application, and it works in every browser but Chrome.
Here is a fiddle:
http://jsfiddle.net/djwelsh/Sxyy8/
In theory it is very simple. Clicking the Start button records the epoch time in milliseconds, and starts a setInterval. On each interval, that starting epoch time is subtracted from the current epoch time. This leaves us with a value in milliseconds, which is converted to h:m:s:cs and displayed on the page.
The problem
My problem is with Chrome. Every time the timer reaches 10000 ms, the tab crashes with the "Aw, snap" message.
One bizarre aspect is that the crash still happens if you hit Stop, wait a few seconds, and then hit Start again. This would seem to indicate that it's a memory issue - something is filling up to the point where it cannot hold any more, and overflowing. But inspecting memory in both dev tools and the resource monitor shows nothing at all unusual.
Possible solutions
The problem can be averted by changing the interval value to a number larger than 100 ms (the default I want to use is 50). It can also be averted by logging the timer values in the console, for some reason.
The trouble is, unless I know why it is happening, I can't be confident that these quick-fixes are actually resolving the problem. I don't want to publish the page until I know it will work in all current browsers.
I know this seems like a fairly narrow-scope problem, but I'm hoping the solution will reveal something larger in scope that might help other people (an idiosyncrasy of Chrome's timer functions or something).
EDIT
By the way, I know that stopping and restarting the timer doesn't work the way it ought to in a real stopwatch; I haven't finished implementing that part yet. I thought it would be better to keep it as simple as possible for SO.
For reference (and great justice), here is the updated version. Still crashes at 10000:
http://jsfiddle.net/djwelsh/Sxyy8/7/
SOLUTION
Based on the answer from #Akhlesh, I updated the fiddle. It now runs properly and acts like a stopwatch: http://jsfiddle.net/djwelsh/Sxyy8/18/
In case you're wondering, I need to use the epoch-based technique (as opposed to just incrementing a base value) because sometimes memory usage issues cause the interval not to be called every second - if the tab is moved to the background while the timer is still running, for example.
You can avoid crashing of tab by making time and now variable as global instead of creating those variable again n again inside Update function.
var uTime,uNow;
//Update function will use same variable to initialize time and now
updateTime: function () {
uNow = Date.now();
oO.milliseconds = uNow - oO.epoch;
uTime = oO.getTimeObject(oO.milliseconds);
oO.el.testClock.text('' + uTime.h + ':' + uTime.m + ':' + uTime.s + ':' + uTime.ms + '');
}
Fiddle Demo
I am not sure about the reason but i think GC is not able to deallocate those variable and same time it allocating new variable and that is causing crash.

Weird bug on Videojs

I don't know how this happens and I can't see any errors.
I can't seem to navigate through the video the second time I open my page.
See screenshot here:
I have found this error it says,
TypeError: Floating-point value is not finite.
"Video is not ready. (Video.js)"
Help would be really appreciated.
Thanks
When you say "I can't seem to navigate through the video the second time I open my page"? Do you mean you aren't able to play the video at all or that you aren't able to fast-forward and rewind within the playing video?
That you are getting a Type Error: Floating-point value is not finite error means that a certain parameter you're supplying to video.js is of the wrong type. I.e. you probaby supply video.js with a string when it wants an integer (or something similar).
Because it works the first time you load the page, are you trying to resume playback where you left off when you navigated away from the page?
If that's the case you are probably storing the currentTime parameter in a cookie or localStorage value as a string (using jQuery cookies for example these usually get automaticalyl stringified) and forgetting to switch it back to an int when you need video.js to read it back to you. Because what I notice about your screenshot is it seems video.js doesn't know the duration of your video (i.e. the seek time says 0:31 / 0:00)
Here's what you should do:
Clear you cache to get a working first time player load then:
Before starting play back, after playback has finished, and during playback you should log the current playback time signature, i.e.: console.log( videojs("id-of-your-video").currentTime() )
Adding time signature console.logs() to these video.js event callbacks should help you:
durationchange (fired if the total duration of your video changes)
duration (tells you the duration of your video. Try logging this while it works and again after it stops working and see what's changed in the value)
If you're still having trouble try logging values using the video js timeupdate callback. This event is called when the current playback position has changed (can be several times a second). If all else fails this callback might give you some insight into the exact moment you're getting the invalid type value, but it won't help you if you're problems are with trying to resume playback from a .currentTime() value reading from an incorrect type stored in user cookie / sessionStorage / localStorage etc.
Are you Using a Server to execute it or are you running it locally. Because I got some similar issues when I ran it locally. But When I put the files in some server like tomcat or iis or whatever servers it worked. Not sure about the issue just a guess

Video on the webpage to autoplay after a set period of time using Javascript/html

I have a video tag on my website but it automaticly starts to play when the websites opens
this is indeed what I want, but I actually want it to start after about 5 seconds
is there a posibility to do so?
You cant do that with pure HTML but with JAVA Script you can use Timing events,
With JavaScript, it is possible to execute some code at specified time-intervals. This is called timing events.
It's very easy to time events in JavaScript. The two key methods that are used are:
setInterval() - executes a function, over and over again, at specified time intervals
setTimeout() - executes a function, once, after waiting a specified number of milliseconds
Note that The setInterval() and setTimeout() are both methods of the HTML DOM Window object.
The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.
window.setInterval("javascript function",milliseconds);
The window.setInterval() method can be written without the window prefix.
The first parameter of setInterval() should be a function.
The second parameter indicates the length of the time-intervals between each execution.
here is an example to Alert hello every 3 seconds
setInterval(function(){alert("Hello")},3000);
Hope this helped.

Categories

Resources