
- server.js
let express = require('express');
let app = express();
app.use(express.static(__dirname));
app.get("/clock", function (req, res) {
res.end(new Date().toLocaleTimeString());
});
app.listen(8080);
- client
<body>
<div id="clock"></div>
<script>
setInterval(function () {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/clock', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.querySelector('#clock').innerHTML = xhr.responseText;
}
};
xhr.send();
}, 1000);
</script>
</body>
- 访问http://localhost:8080/clock

- client
<body>
<div id="clock"></div>
<script>
setInterval(function () {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/clock', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.querySelector('#clock').innerHTML = xhr.responseText;
}
};
xhr.send();
}, 1000);
</script>
</body>
- server.js
let express = require('express');
let app = express();
app.use(express.static(__dirname));
app.get("/clock", function (req, res) {
//优化: 当时间为每隔5的倍数才返回.
let $timer = setInterval(function () {
let date = new Date();
let seconds = date.getSeconds();
if (seconds % 5 === 0) {
res.end(new Date().toLocaleTimeString());
clearInterval($timer)
}
}, 1000);
});
app.listen(8080);原文:https://www.cnblogs.com/iiiiiher/p/12209115.html