I have a video and series of comments on the video. Each comment has a specific time associated with the video. For example video 1 has 3 comments. one in second 15, another in second 30, and the last comment is in second 45.
I can show all the comments. However, instead I want each comment to be shown on its associated time of the video. For example, comment 1 should only be appeared in second 15 and lasts until second 30 where it is replaced by second comment and so on.
I'm using JW Player to play the video and can get getPosition() function to get the current elapsed time of the video. It should be a simple JavaScript code to achieve this but unfortunately I'm so beginner with JS.
My own idea to achieve this is to use onTime function and for each position check if there is a comment in the server or not, and retrieve if there is. As in:
<script>
jwplayer("container1").onTime(
function(event) {
{
var comment = get_comment_of(event.position);
setText(comment);
function setText(text) {
document.getElementById("message").innerHTML = text;
}
});
</script>
However, this is an expensive function and will send huge number of requests to the server.
Ok, the best solution I have preloaded the comments in a javascript array when the page is loaded, then show them when they occur using onTime function. This way there is no need to send a new request on on every onTime frame. As the comments are already available on the client side
var timeArray = <?php echo json_encode($timeArray) ?>;
var commentArray = <?php echo json_encode($commentArray) ?>;
jwplayer("container1").onTime(
function(event) {
for (var i = 0; i < timeArray.length; i++)
{
var time = timeArray[i]
var comment = commentArray[i];
if (event.position >= time) {
setText(comment);
}
}
function setText(text) {
document.getElementById("message").innerHTML = text; }
}
);
Related
I'm trying to make a website load forever. My current idea is to request a PHP file:
<?php
sleep(30);
This will delay the load by 30 seconds, which a quick Google search tells me should be within most browsers' timeouts. I was thinking of writing some JavaScript to append a new link tag after a bit less than 30 seconds to keep the page loading, but I found that this didn't keep the loading icon spinning (with Chrome at least):
window.addEventListener( 'load', () => {
var i = 0;
setInterval( () => {
i++;
var newScript = document.createElement('script');
newScript.src = 'infinite-loading.php?i=' + i;
document.querySelector('#infinite-loading').after(newScript);
console.log('The deed is done');
}, 25000)
} )
<script id="infinite-loading" src="infinite-loading.php"></script>
The code above appends a script tag every 25 seconds, and the browser loads the PHP file each time, but it doesn't show the loading icon. I added the URL parameter because I wasn't sure if browsers would cache the page.
I also want to make sure that the server with the PHP file won't be overloaded. I'm not sure if many sleep() functions running constantly at the same time will cause any issues.
Is there a better way to do this client-side? Should I use something other than PHP? Something multi-threaded?
(Edit: Sorry for the awkward title, Stack Overflow didn't like my first one.)
You need that browser will continue reading your page forever (I'm talking about HTML, not other linked objects). So you need not to break timeout and feed some data from backend to frontend.
Example of sending portion of data to client:
ob_end_flush();
# CODE THAT NEEDS IMMEDIATE FLUSHING
ob_start();
Now we need to understand the minimum data packet size that is expected by the browser. Minimal googling tells us a limit of 8-10 bytes.
So combining this together we can try to check (I did not checked, it is just my version):
<?php
while (true) {
sleep(25);
ob_end_flush();
echo " "; // 10 spaces...
ob_start();
}
Not sure why you would want to do anything like this but the simplest solution I think is an endless loop.
<?php
while(true)
{
}
First things first: I don't know anything about coding and I basically build my whole HTML file by CMD+C and CMD+V what I found with lots of Google searches and change just what is needed so it fits into what I intended. Interestingly I got a result that is 95% what I wanted.
Now I have just one last thing I can't set (or find about in Google) so hopefully someone can answer it here. [Trying to put in as many information as I can]
I made a simple one page HTML that shows the date/time and plays an audio livestream from my PC when opened.
I also want it to display the "Now Playing" information. After a lot of searches, I finally found a solution that even I could make with Dreamweaver.
I used the "fetch script" (or is it called Fetch APP?) to get a txt file that my music player gives as output with the current song information. That fetch script get the data and put it into a
The problem is that is only seems to do it once at page load and not every few seconds. The contents in the txt change whenever a new song plays and I want the displayed data on the HTML to stay current as well.
So how do I set that fetch script to re-fetch the txt contents every ~10 seconds?
Here is my current fetch script:
<script>
var url = 'NowPlaying.txt';
var storedText;
fetch(url)
.then(function(response) {
response.text().then(function(text) {
storedText = text;
currentSong();
});
});
function currentSong() {
document.getElementById('thesong').textContent = storedText;
}
</script>
For making my HTML I use "Dreamweaver 2019" on "Mac OS 11 Big Sur"
It's a single HTML and all files/assets the HTML accesses (The Audio, Background Images and the TXT file are in the same directory/network)
I hope that provides all necessary details.
Oh and what I tried already is to copy the line "var t = setTimeout(fetch, 100);" into the script, because this seems to be what keeps the clock javascript current and I hoped it would do the same with fetch
Also attached a screenshot of the HTML "live" in chrome >> screenshot
As you can see, the bottom is supposed to have the "Now Playing" information displayed (please ignore that in this example the text is cut to the right, the current information is too long, so it cuts off at the end)
You cam simply use setInterval to call your fetch every 10th seconds.
Just wrap your function in to a function and call that function in setInterval.
=> Also, at sometime if you would like to stop the fetch request on an event like a button click or something you can use clearInterval to stop the fetch request without refreshing the page.
Run snippet below to see the function is getting called every 10th seconds.
var url = 'NowPlaying.txt';
var storedText;
//10 Seconds fetch
function fetch10Seconds() {
//Fetch
fetch(url)
.then(function(response) {
response.text().then(function(text) {
storedText = text;
currentSong();
});
});
console.log('Fetch again in 10 Seconds')
}
//Call function every 10 seconds
setInterval(fetch10Seconds, 10000); // 10 seconds are defined in miliseconds
//Call this on fetch every 10 seconds
function currentSong() {
document.getElementById('thesong').textContent = storedText;
}
You can create a loop using setInterval function
var url = 'NowPlaying.txt';
var storedText;
setInterval(()=>{
fetch(url)
.then(function(response) {
response.text().then(function(text) {
storedText = text;
currentSong();
});
});
},10000) // in miliseconds
function currentSong() {
document.getElementById('thesong').textContent = storedText;
}
Try this:
function doFetch() {
setTimeout(() => {
fetch(url)
.then(response => {
response.text().then(text => {
storedText = text;
currentSong();
doFetch();
});
});
}, 10000);
}
doFetch();
This waits for the data to be fetched before waiting another 10 seconds and fetching again. Using setInterval will get the data every 10 seconds on the dot regardless of the success of the last run of the function.
I have been searching on the net for a code that refreshes the chat <div> every time a new message is received from the other chat user. I have read about setTimeout() and setInterval() however need more experienced developers advice and help.
The best example is this website. Unless you refresh the browser, you will not see the notification right away. I guess the best example is facebook. Whenever the Database is updated, the notification is popped up right away without refreshing the browser.
Here`s my code.
$check_sql = ("SELECT time from messages where conversation_id = '".$con_id."' ");
$check_query = mysqli_query($con, $check_sql) or die ("ERROR checking:".mysqli_error($con);
while($row = mysqli_fetch_assoc($check_query){
$current_time = date_default_timezone_get();
$message_time_sent = $row['time'];
$cal = $message_time_sent->diff($current_time);
$ans = $cal->format("%D %H:%i:%s");
sscanf($ans,"%d %d:%d:%d ", $day, $hr, $min, $sec);
if (($day == 0) && ($hr == 0) && ($min == 0) && ($sec >0)){
//do something here to get receive message automatically and notification....
}
What I want to achieve:
Facebook automatically receives messages without refreshing the browser. I hope it could be like this.
Automatic pop up of notification without refreshing the browser which I think it is not really important, once we can figure out item 1, then the rest will be all good.
The tricky part about using setInteval() the browser will keep refreshing the <div> chat so when the user input a text to send, it will disappear everytime it refreshes. Please excuse my English....
So, is there a proper way of handling this....
setInterval - set interval will call your function every interval you set
setInterval sample: https://repl.it/OE1o
<html>
<body>
<div id="sample">
Day Mon DD YYYY HH:MM:SS GMT+XXX (Time Zone)
</div>
</body>
</html>
<script>
var sample = document.getElementById('sample');
setInterval(
// Here is where to do things like dom manipulation
function() {
sample.innerHTML = new Date;
},
// Here is where you set the interval asuming I want to update every 1 second
1000
);
</script>
setTimeout - will be call once the timeout is reached.
setTimeout sample: https://repl.it/OE3H
setTimeout(
// This function will be called once the timeout is reached
function() {
console.log('Hello World');
},
// The timeout is 5 seconds
5000
);
I'm trying to write KDE4 plasmoid in JavaScript, but have not success.
So, I need to get some data via HTTP and display it in Label. That's working well, but I need regular refresh (once in 10 seconds), it's not working.
My code:
inLabel = new Label();
var timer= new QTimer();
var job=0;
var fileContent="";
function onData(job, data){
if(data.length > 0){
var content = new String(data.valueOf());
fileContent += content;
}
}
function onFinished(job) {
inLabel.text=fileContent;
}
plasmoid.sizeChanged=function()
{
plasmoid.update();
}
timer.timeout.connect(getData);
timer.singleShot=false;
getData();
timer.start(10000);
function getData()
{
fileContent="";
job = plasmoid.getUrl("http://192.168.0.10/script.cgi");
job.data.connect(onData);
job.finished.connect(onFinished);
plasmoid.update();
}
It gets script once and does not refresh it after 10 seconds. Where is my mistake?
It is working just fine in here at least (running a recent build from git master), getData() is being called as expected. Can you see any errors in the console?
EDIT: The problem was that getUrl() explicitly sets NoReload for KIO::get() which causes it load data from cache instead of forcing a reload from the server. Solution was to add a query parameter to the URL in order to make it force reload it.
My question is Client time only displayed, But want to display server time every seconds.
function GetCount(ddate,iid){
var date = new Date();
dateNow = date;
// if time is already past
if(amount < 0){
}
// else date is still good
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
document.getElementById(iid).innerHTML=days;
document.getElementById('countbox1').innerHTML=hours;
document.getElementById('countbox2').innerHTML=mins;
document.getElementById('countbox3').innerHTML=secs;
setTimeout(function(){GetCount(ddate,iid)}, 1000);
}
}
If you want to avoid all that network traffic checking the time with the server every second just: (1) have the server pass the time in a way that you store in a JS variable on page load; (2) also store the client time as at page load; (3) use setInterval to update the time (every 1000 milliseconds or as often as you want) by getting current client time minus client time at page load as an offset of server time at page load. (Obviously this will all go wrong if the user updates their PC clock while your page is running, but how many users would do that? And would it be the end of the world if they did?)
If you really want the actual server time every second - why? Seems a bit of a waste of bandwidth for little if any benefit, but if you must do it use Ajax as already suggested. If you're not familiar with Ajax I'd suggest using Google to find some tutorials - if you use JQuery you can do it with only a couple of lines of code. Easy.
Or put your onscreen clock in an IFRAME that repeatedly reloads itself. Just because I sometimes miss the days of IFRAMEs.
If you run into the issue that the server time is different from the client-side clock, I lookup a server time delta in minutes just once, and then I add it to the minutes of a new Date():
var refDateTime = new Date();
refDateTime.setMinutes(refDateTime.getMinutes() + getServerTimeDelta());
// ...
var serverTimeDelta;
function getServerTimeDelta(recalc) {
var xmlHttp;
if (recalc || !serverTimeDelta) {
try {
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
} catch(err1) {
//IE
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
} catch(err2) { /* swallow it */ }
}
if (xmlHttp) {
xmlHttp.open('HEAD', window.location.href.toString(), false);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send('');
var serverDateTime = xmlHttp.getResponseHeader("Date");
if (serverDateTime) {
var dateNow = new Date();
var serverDate = new Date(serverDateTime);
var delta = serverDate.getTime() - dateNow.getTime();
// Convert to minutes
serverTimeDelta = parseInt((delta / 60000) + '');
if (!serverTimeDelta) serverTimeDelta = 0.01;
} else {
serverTimeDelta = 0.011; // avoid auto recalc
}
} else {
serverTimeDelta = 0.012;
}
}
return serverTimeDelta;
}
You need your server to supply the time to JavaScript, either on page load or via XMLHttpRequest.
To get the server time from the client side in javascript you will need to make an ajax call.
Do you know how to make that type of call?
You will basically make another page (or web method etc) which displays/returns the time. You will then use a XMLHttpRequest object to make the call and get the result.