[英]Reload contents of text file every 10 seconds
我有以下代码,该代码允许用户选择文本文件,然后将内容加载到下面的PRE标签中。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Load text file</title> <script type="text/javascript"> function readText(that){ if(that.files && that.files[0]){ var reader = new FileReader(); reader.onload = function (e) { var contents = e.target.result;//.replace("\\r\\n","<br/>"); contents = contents.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); document.getElementById('board').innerHTML= contents; };//end onload() reader.readAsText(that.files[0]); }//end if html5 filelist support } </script> </head> <body> <input type="file" onchange='readText(this)' /> <hr /> <pre id="board" contenteditable = "true"> This is where the text from the chosen text file will be loaded. </pre> </body> </html>
是否可以每10秒读取一次所选文件的内容?
例如,用户选择文本文件(一次)。 然后,代码循环并重新读取内容,并使用可能已对文本文件进行的任何更改来更新PRE标签。
我在本地工作,因此无法使用任何服务器脚本。
我觉得解决方案可能涉及SETINTERVAL?
谢谢。
您可以使用
// A variable to store the id of the setInterval method
var currentIntervalId = undefined;
// The function that calls your method.
var startOrRestart = function(that) {
// Clear the 'old' calls to avoid wrong behavior
if (currentIntervalId !== undefined) clearInterval(currentIntervalId);
readText(that); // For executing immediately
// Execute it readText each 10 seconds
currentIntervalId = setInterval(function() { readText(that); }, 10000);
};
然后在输入标签中调用
<input type="file" onchange='startOrRestart(this)' />
此解决方案的想法是,您每隔10秒钟执行一次readText(that)函数(借助于setInverval函数)。 但是,如果文本更改,则将再次执行setInterval函数。 因此,您有一个旧的“触发器”来处理“旧”输入。 并且您为新输入输入了一个新的“触发器”。 为了避免这种不良行为,我们存储了触发器的ID,并在设置了触发器后将其杀死。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.