向客户发送信息的 javascript 函数?
A javascript function that sends infos to clients?
我在 Javascript 中创建了一个小脚本,它应该向页面上连接的所有客户端显示一些信息,实际上是每 90 秒显示一张图像。这个功能在我的电脑上运行得很好,但是一旦我必须重新加载页面,所有进程都会重新启动。
不知道有没有办法让服务端调用这个函数,像这样
//This should be a "server" variable in which users should be able to add their own image :
var images = [
['Canyon', 'https://www.w3schools.com/css/img_fjords.jpg'],
['Car Jumping', 'http://www.gettyimages.fr/gi-resources/images/Embed/new/embed2.jpg'],
['Birds Flying', 'http://ekladata.com/qWGncUdJ7U5k2vvmc1au-ZLnjlc.jpg'],
];
function Display (imagesarray) {
var rnd = Math.floor((Math.random() * imagesarray.length - 1) + 1);
document.getElementById("image").src = imagesarray[rnd][1];
}
function Timer(countDownDate) {
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now + 2;
// Time calculations for days, hours, minutes and seconds
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("countdown").innerHTML = ("0" + minutes).slice(-2) + ":" + ("0" + seconds).slice(-2);
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "FINISHED !";
Display(images);
}
}, 1000);
}
//This will call the Timer() function to end it in 01:30, and launch it again 10 seconds after the end of the previous call.
var y = setInterval(Timer(new Date().getTime() + 10000), 500);
p {
text-align : center;
font-size : 48px;
margin : 0px;
}
#note {
text-align : center;
font-size : 12px;
margin : 0px;
}
#image {
display : block;
margin : auto;
width : 150px;
height : 150px;
}
<p id="note">Counting only 10 seconds for example</p>
<p id="countdown">00:10</p>
<img id="image" src="http://vignette4.wikia.nocookie.net/destinypedia/images/b/b9/Unknown_License.png/revision/latest?cb=20130810221651">
有谁知道服务器是如何管理的,所以每个人都有相同的计时器和相同的图片同时显示?
非常感谢您的帮助!
[编辑 1] 我在这个项目上使用的后端语言是 PHP
您可能需要通过 websockets 与服务器保持持久连接,或者您可以轻松地从服务器发送一个变量,告诉客户端下一次出现应该在多少秒后开始。
突发新闻:时间在世界各地都以同样的方式流逝:-D。
所以没有真正需要 "persistent connection" 左右,只要用户在他们的计算机上正确设置时间即可。您只需要为每个用户使用相同的基准日期。时间戳在这方面非常擅长,因为它们没有时区问题。
另请注意,最好不要使用 setTimeout
setInterval
来测量时间,因为 setTimeout
可以重命名为 runAfterAtLeastThatTimeIfYouDontHaveBetterToDo()
。实际上,放置 setIterval(()=>{},1000)
并不能保证它每 1 秒就会 运行,并且如果用户在浏览时切换选项卡,您可能会遇到不同步的情况。你最好 运行 间隔函数比每隔一秒多一次——例如每 10 毫秒——如果你想让它准确的话。
平时,我用requestAnimationFrame
来显示定时器。
代码:
在这段代码中,我为每个用户使用相同的基准日期(我没有放任何 10 秒的冷却时间,因为我很懒,但你可以看到这个想法):
const startDate = 0; // Unix epoch
const interval = 90000; // 90 seconds
var now = Date.now();
var count = (now - startDate) / interval; // should have run {{count}} times since Unix epoch
var next = Math.ceil(count) * interval + startDate; // so the next time it should run is at timestamp {{next}}
function timer() => {
var now = Date.now();
distance = next - now;
if (now >= next) {
document.getElementById("image").src = "http://domain.tld/my-script.php?now=" + now; // the query string parameter is just to avoid browser caching the image
next += interval;
} else {
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("countdown").innerHTML = ("0" + minutes).slice(-2) + ":" + ("0" + seconds).slice(-2);
}
}
var requestID = window.requestAnimationFame(timer);
// use window.cancelAnimationFrame(requestID) to cancel the timer
关于 img.src
部分的注释:
这是唯一需要服务器的部分,您必须实现一个脚本,该脚本将根据时间发送图像。我添加了一个 queryString ?now=timestamp
来避免浏览器缓存图像,而不是保持它是最新的,但是服务器应该依靠它自己的 date/time 来显示图像,而不是用户发送的图像。
PS : 请注意,我没有反对通过 websocket 等进行持久连接的任何东西,但是对于仅显示计时器和图像定期。如果您认为您的所有用户都正确设置了他们的计算机时间,并且如果有些用户不同步也没什么大不了的,请使用此解决方案。否则,请使用 websocket。
我在 Javascript 中创建了一个小脚本,它应该向页面上连接的所有客户端显示一些信息,实际上是每 90 秒显示一张图像。这个功能在我的电脑上运行得很好,但是一旦我必须重新加载页面,所有进程都会重新启动。
不知道有没有办法让服务端调用这个函数,像这样
//This should be a "server" variable in which users should be able to add their own image :
var images = [
['Canyon', 'https://www.w3schools.com/css/img_fjords.jpg'],
['Car Jumping', 'http://www.gettyimages.fr/gi-resources/images/Embed/new/embed2.jpg'],
['Birds Flying', 'http://ekladata.com/qWGncUdJ7U5k2vvmc1au-ZLnjlc.jpg'],
];
function Display (imagesarray) {
var rnd = Math.floor((Math.random() * imagesarray.length - 1) + 1);
document.getElementById("image").src = imagesarray[rnd][1];
}
function Timer(countDownDate) {
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now + 2;
// Time calculations for days, hours, minutes and seconds
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("countdown").innerHTML = ("0" + minutes).slice(-2) + ":" + ("0" + seconds).slice(-2);
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "FINISHED !";
Display(images);
}
}, 1000);
}
//This will call the Timer() function to end it in 01:30, and launch it again 10 seconds after the end of the previous call.
var y = setInterval(Timer(new Date().getTime() + 10000), 500);
p {
text-align : center;
font-size : 48px;
margin : 0px;
}
#note {
text-align : center;
font-size : 12px;
margin : 0px;
}
#image {
display : block;
margin : auto;
width : 150px;
height : 150px;
}
<p id="note">Counting only 10 seconds for example</p>
<p id="countdown">00:10</p>
<img id="image" src="http://vignette4.wikia.nocookie.net/destinypedia/images/b/b9/Unknown_License.png/revision/latest?cb=20130810221651">
有谁知道服务器是如何管理的,所以每个人都有相同的计时器和相同的图片同时显示?
非常感谢您的帮助!
[编辑 1] 我在这个项目上使用的后端语言是 PHP
您可能需要通过 websockets 与服务器保持持久连接,或者您可以轻松地从服务器发送一个变量,告诉客户端下一次出现应该在多少秒后开始。
突发新闻:时间在世界各地都以同样的方式流逝:-D。
所以没有真正需要 "persistent connection" 左右,只要用户在他们的计算机上正确设置时间即可。您只需要为每个用户使用相同的基准日期。时间戳在这方面非常擅长,因为它们没有时区问题。
另请注意,最好不要使用 setTimeout
setInterval
来测量时间,因为 setTimeout
可以重命名为 runAfterAtLeastThatTimeIfYouDontHaveBetterToDo()
。实际上,放置 setIterval(()=>{},1000)
并不能保证它每 1 秒就会 运行,并且如果用户在浏览时切换选项卡,您可能会遇到不同步的情况。你最好 运行 间隔函数比每隔一秒多一次——例如每 10 毫秒——如果你想让它准确的话。
平时,我用requestAnimationFrame
来显示定时器。
代码:
在这段代码中,我为每个用户使用相同的基准日期(我没有放任何 10 秒的冷却时间,因为我很懒,但你可以看到这个想法):
const startDate = 0; // Unix epoch
const interval = 90000; // 90 seconds
var now = Date.now();
var count = (now - startDate) / interval; // should have run {{count}} times since Unix epoch
var next = Math.ceil(count) * interval + startDate; // so the next time it should run is at timestamp {{next}}
function timer() => {
var now = Date.now();
distance = next - now;
if (now >= next) {
document.getElementById("image").src = "http://domain.tld/my-script.php?now=" + now; // the query string parameter is just to avoid browser caching the image
next += interval;
} else {
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("countdown").innerHTML = ("0" + minutes).slice(-2) + ":" + ("0" + seconds).slice(-2);
}
}
var requestID = window.requestAnimationFame(timer);
// use window.cancelAnimationFrame(requestID) to cancel the timer
关于 img.src
部分的注释:
这是唯一需要服务器的部分,您必须实现一个脚本,该脚本将根据时间发送图像。我添加了一个 queryString ?now=timestamp
来避免浏览器缓存图像,而不是保持它是最新的,但是服务器应该依靠它自己的 date/time 来显示图像,而不是用户发送的图像。
PS : 请注意,我没有反对通过 websocket 等进行持久连接的任何东西,但是对于仅显示计时器和图像定期。如果您认为您的所有用户都正确设置了他们的计算机时间,并且如果有些用户不同步也没什么大不了的,请使用此解决方案。否则,请使用 websocket。