So I am working on an interactive HTML5 video player, and currently have everything working while using popcorn.js, but I am now trying to go back and make my player work without being dependent on popcorn.js.
When working with popcorn.js, you can use code like:
popcorn.code((
start: 0,
end: 5,
onStart: function( options ) {
//put code here
}
}}
and your code will be executed when the time of your video spans from 0 through 5. Now, I am trying to have certain blocks of code executed within a certain timeframe of the video, but i can't seem to get it working right and was just wondering if someone can see where i am going about this wrong.
while (myVideo.currentTime >= 0 && myVideo.currentTime <= 5)
{
console.log(myVideo.currentTime);
}
This while loop is also running so fast that it causes the browser to slow down and freeze.
However, if i try using an if loop instead of a while loop, it (obviously) only checks it once.
You could check fewer than the while loop would.
var check = setInterval(function() {
if (myVideo.currentTime >= 5) {
clearInterval(check);
console.log("5 seconds reached");
}
}, 500);
You than can start this again when the user pauses and starts over or if he jumps to another time within the timeline.
Try using the following so your function will run only once every second.
setInterval(function(){
if(myVideo.currentTime >= 0 && myVideo.currentTime <= 5){
console.log(myVideo.currentTime);
}
},1000);
Good luck!
Related
I have some images that I am displaying through JSON. This file refreshes the content every 10 seconds so the new images added show without a page refresh.
I am struggling to add a slideshow code without the two refresh's clashing with each other.
I would really appreciate some help.
This is my current code.
function update_content() {
$.getJSON("showImages.php", function(data) {
$("#slides").html(
data.result.map(({image1}) => `<img class="slides" src="data:image/png;base64,${image1}" />`).join("")
);
setTimeout(update_content, 10000);
var index = 0;
slideshow();
function slideshow() {
var i;
var x = document.getElementsByClassName("slides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
index++;
if (index > x.length) {index = 1}
x[index-1].style.display = "block";
setTimeout(slideshow, 20000);
}
})
}
$(function() {
update_content()
})
The way this is written, there's no way the refreshes wouldn't clash with each other and cause a large mess in updating. What you have here will, every 10 seconds, do a ping back to the server for some json and then spawn what is essentially a thread (not in the technical sense, but in the behavior sense) that every 20 seconds hides all the slides and shows the first slide. By about 60 seconds into this page running, you now have six instances of the slideshow() function queued to run, the newly created one trying to show the first slide, the next most recently created two showing the second, the next two showing the third, etc. And because network lag is unpredictable, they'll all fire at slightly different times in an unpredictable order.
The main problem is setTimeout(slideshow, 20000). It's not needed as this is currently written. Slideshow() is being run every 10 seconds already from the outer function running every 10; it doesn't need to run separately in its own timeout. And if you're running it at that interval already, the slideshow function is useless anyway, and the server only needs to return one image in its json, and the whole slideshow function can be deleted.
Though I question why you need to do a network round-trip every 10 seconds to begin with. Unless this is some real-time snapshot of a camera feed or something, you can easily just give javascript a large array of images for it to cycle through and maybe do the server ping for new images every 10 minutes or so instead. If you go this route, instead move slideshow() out of the update_content() function and just call it once from the jquery onready function to set it running and leave it be. If you need to call slideshow() in the getJson callback, be sure to cancelTimeout on the previous setTimeout(slideshow, ...)'s return value, so you don't make pseudo-threads as described above.
I have been trying to create a Javascript simple program that checks for words on a specific web page and I am just wanting it to check every 5 seconds or so if the words are there. I think I have the pieces of the puzzle but I just cant put it together. I am a beginner at best and don't understand why this code is not working.
This is what I have but the iteration after searching for the word and reloading the page to check again are not in sync and the page reloads once. It should be checking if word is there, if it is there then I am trying to get it to reload page and check again and loop again .... every 5 seconds. Current output with below code is "true" in an alert box twice then reload after 5 seconds once. And it's over.
Note:
x just stops from looping forever.
When it doesn't match any more it plays a song.
I saved this as a .js file and I am currently just testing the code within chrome dev tools.
'''
var x = 1;
function ol(){
do {
if (document.documentElement.outerHTML.search('8"},"availability_html":"<p class=\\\\"stock out-of-stock') != -1)
{
x=x+1;
alert("true");
window.setTimeout(function ol() {
window.location.reload(true);
}, 5000);
} else {
alert("NOT FOUND!");
var snd1 = new Audio("C:\Users\DL\Desktop\bot files\BattleMetal-320bit.mp3");
function beep1()
{alert()
snd1.play()
beep1()
}
}
}while(x<3 && document.documentElement.outerHTML.search('8"},"availability_html":"<p class=\\\\"stock out-of-stock') != -1);
}
ol();
In the while condition you are checking if x < 3. so after printing twice true you are explicitly stopping the loop.
I am making a small userscript for a survey site. Whenever I click the survey and it is indicated that I did not receive it the script is supposed to refresh a certain amount of times trying to claim the survey until it gives up.
(If you do not know what a userscript is, think of it as something that stays running all the time on a specific website, so you can control things using javascript selectors and stuff)
This is my script so far (the javascript portion as that is what the problem is in):
var elementExists = document.getElementsByClassName("message warning")[0];
if(elementExists)
{
var attempts = 0;
while(attempts<5)
{
attempts += 1;
location.reload();
if(elementExists)
{
//nothing
}
else
{
window.stop();
}
}
window.stop();
}
This is actually my first time using Javascript so I assumed that would be the reason for errors, but after 45 minutes of debugging I am completely baffled. If I remove that last "window.stop();" the code refreshes the webpage infinitely. If that stays there then the code doesn't even start. It seems almost as if the while loop is being skipped if the "window.stop();" is present. Is this something that Javascript does, or is the problem elsewhere?
If someone could lead me in the right direction or help me fix this I would be very grateful!
(Also I checked the selector to see if that is the issue, but I have done that correctly)
UPDATE: Turns out location.reload(); stops the script and thus forces a reload. Since I am creating a userscript I realized that I could use the Greasemonkey APIs (or more like stumbled upon). By using GM_setValue and GM_getValue I was able to work around this problem and the script successfully reloaded a certain amount of times (depending on the variable tries) and stopped when it finished. But after messing around a bit, then reverting to the older version the script, the script doesn't doesn't execute at all anymore; "counter < tries" seems to be false for some reason... could anyone figure out why? Also if documentation is needed:
https://wiki.greasespot.net/GM_getValue
https://wiki.greasespot.net/GM_setValue
var tries = 5;
var elementExists = document.getElementsByClassName("message warning")[0];
var counter = GM_getValue('counter', 0);
if(elementExists && counter < tries)
{
GM_setValue('counter', ++counter);
location.reload();
}
(Both counter and tries seem to be integer values.. so there should be in problem in comparing them...)
Also as suggested by #yuriy636 I attempted to reset the variables and created something like this
var tries = 5;
var elementExists = document.getElementsByClassName("message warning")[0];
var counter1 = GM_getValue('counter1', 0);
if(elementExists && counter1 < tries)
{
GM_setValue('counter1', ++counter1);
location.reload();
}
if(elementExists && counter1 == tries)
{
GM_deleteValue('counter1');
window.close();
}
if(!!elementExists)
{
GM_deleteValue('counter1');
return;
alert("stops script while hidden");
}
But again I am hit with the infinite loop.. RIP
Update 2: Not so RIP afterall... solution:
var tries = 50;
var elementExists = document.getElementsByClassName("message warning")[0];
var counter = GM_getValue('counter', 0);
if(elementExists && counter < tries)
{
GM_setValue("counter", counter + 1);
location.reload();
}
else
{
GM_deleteValue("counter");
}
if(elementExists && counter >= tries)
{
window.close();
}
100% Working, after indicated amount of tries, if error still exists the page is closed
The most likely problem is that you have location.reload() in your while loop. This causes the page to refresh before anything interesting happens in your loop. In this particular code I would expect the page to refresh seemingly infinitely because every time the page refreshes, it will refresh again.
Normally this would look more like:
var elements = document.getElementsByClassName("message warning");
for (var i = 0; i < elements.length; i++) {
console.log (elements[i]);
}
.getElementsByClassName returns an array of elements with the class message and/or warning which you are capturing only the 1st one [0]. Hope that helps.
I have a small piece of code that continuously clicks a button called "See Older Messages" every 500 ms, in order to load infinitely-scrolled content from a webpage. Reasons for doing this are personal, but needless to say, I'm trying to automate something which would take me weeks of non-stop scrolling to do otherwise.
The problem is that the 500 ms delay gradually begins to drop as the script runs over time. After so many hours, it can take 5 seconds or more. I'm assuming this problem is caused by Facebook throttling my requests after so long, so to prevent this, I want to make the script run for an amount of time - say 2 minutes - followed by a delay of maybe 20 secs before it runs again for 2 mins, and so on. How would I go about doing this? I've racked my brains, but my limited knowledge of JavaScript hasn't come up with anything meaningful.
Below is the current code in its entirety.
setInterval(function () {
document.getElementById('see_older').getElementsByClassName('content')[0].click();
}, 500);
Thanks a lot in advance.
Keep track of when the script running started
While it's been less than 2 mins, keep clicking every 500ms.
After running for ~2 mins, stop and queue next run in 20s.
Go to step 2.
-
var lastChange;
function doClick() {
if (new Date() - lastChange < 120000 /* 2 mins */) {
document.getElementById('see_older').getElementsByClassName('content')[0].click();
setTimeout(doClick, 500);
} else setTimeout(runScript, 20000 /* 20s */);
}
(function runScript() {
lastChange = new Date();
doClick();
})();
-
I recommend using setTimeout over setInterval since, if the browser takes a while to execute, loses focus and stops executing JS, gets paged out, etc., then you will still get the time spacing between events that you want. See https://stackoverflow.com/a/731625/1059070.
Toggle whether or not your function does anything by setting another timer.
/* When true do load else don't. */
window.doLoad = true
setInterval(function () {
if window.doLoad {
document.getElementById('see_older').getElementsByClassName('content')[0].click();
}
}, 500);
/* This will toggle doLoad every two minutes. */
setInterval(function () {
if (window.onLoad == true) {
window.doLoad = false;
} else { window.doLoad = true; }
}, 120000); // two minutes of milliseconds
In your case though you might be better off using the Facebook Graph API.
Graph API documentation from Facebook
Here's an existing question with the API using Python to do basically the same thing you want to do.
JS question, also similar
I'm writing Javascript which is counting up to a certain number for a project. The number could be around 100,000 and It will take roughly 10-15 seconds to complete processing.
I want the script to run as soon as the user calls the page and when the script completes it does a redirect.
Is it possible to pause for even 10ms to update the DOM while it is running to give feedback such as "Still working"?
I would like to avoid the use of jQuery and web-workers are not an option in this situation.
I realise this isn't a real world application!
EDIT: Added some of the code as a sample:
In the head
function myCounter (target) {
var t = target;
var count = 0;
while (t != count){
if (t == count) {
window.location.replace("http://example.com"); // redirect
}
count++;
}
}
In the body
<script>myCounter(100000);</script>
In most browsers JavaScript and the UI run in the same thread. You can give the thread back to the browser by using setTimeout (or setInterval).
var myNumber = 0;
updateNumber();
function updateNumber(){
// do heavy work for great good, ideally divided into smaller chunks
document.getElementById('updateDiv').innerHTML = 'still working, up to ' + myNumber;
if(myNumber < limit) {
setTimeout(updateNumber, 20);
}
}
For a lot more details on the general process, this answer is worth a read: https://stackoverflow.com/a/4575011/194940