【问题标题】:Javascript function to reload page if certain conditions are met is reloading page infinitely如果满足某些条件则重新加载页面的Javascript函数是无限地重新加载页面
【发布时间】:2020-11-25 20:17:22
【问题描述】:

所以总的来说,我对 JavaScript 和 Web 开发还很陌生。我正在尝试编写一个脚本来重新加载网页,如果:

一个。 “forum.html”文件已更新

b.名为“聊天”的文本框不为空。

这听起来很简单,但我已经设法以某种方式超越了自己的头脑。该脚本似乎完成了它的设计目标。首先。但随后不知何故陷入了重新加载地狱的愤怒,并在尝试(我假设)无限次重新加载页面后使网页无法使用。

我将把脚本留在这里:

function timer() {
}

//rest time
setTimeout(timer, 10000);

function ifThen() {
  while (0 == 0) {
    setTimeout(timer, 1000);
    if (form.chat.value == "") {
      break;
    }
  }
}

function mything() {
  fetch('forum.html')
    .then(response => response.text())
    .then((data) => {
      setTimeout(timer, 7500);
      fetch('forum.html')
        .then(response => response.text())
        .then((data2) => {

          if (data !== data2) {
            setTimeout(ifThen, 100);
            location.reload();
          }
          delete(data2);
      })
      delete(data);
  })
}
setInterval(mything, 100);

【问题讨论】:

  • 小心while (0 == 0)之类的东西。
  • @technophyle 我已经注意到这个小家伙了。我尝试了其他不包含 while 的排列,但基本上都没有成功。
  • 我不认为这个setTimeout(timer, 7500); 正在做你认为它正在做的事情。我想你在找sleep(7500) See here for example
  • @David JS 有睡眠功能吗?我一直在寻找这些信息,但在 javascript“睡眠功能”上找不到任何内容
  • 我自己对它不是很熟悉,但它确实存在。 setTimeout 是异步的,因此它实际上不会暂停您的执行。

标签: javascript function reload


【解决方案1】:

您使用 setTimeout 的方式不起作用。 setTimeout 是一个异步工作函数。空的 timer 函数在过期时间后执行,仅此而已。 while 循环也很重要。

阅读有关承诺、同步和异步模式的更多信息,以更好地了解如何组织代码。

总的来说,这应该是一个单一的间隔,即定期再次轮询文件并将其与原始文件进行比较。 interval 类似于 timeout,只是在特定的时间间隔到期后重复执行。

我不确定,IfElse 函数是干什么用的,我暂时忽略了它,但解决方案可能如下所示。

解决方案

setTimeout(() => startCheck(7500), 10000);

function getData() {
  return fetch("forum.html");
}


async function startCheck(intervalMs) {
  const originalData = await getData();

  setInterval(async () => {
    const newData = await getData();
    
    if (originalData !== newData) {
      location.reload();
    }
  }, intervalMs);
}

【讨论】:

    【解决方案2】:

    while(0 == 0) 是一个永远不会终止的繁忙循环,setTimeout 不会阻止它,它只是在后台启动一个计时器。请改用a promise-based sleep with async/await

    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
    
    async function ifThen() {
      while (0 == 0) {
        await sleep(1000);
        if (form.chat.value == "") {
          break;
        }
      }
    }
    
    async function mything() {
      const res = await fetch('forum.html');
      const data = await res.text();
      setTimeout(timer, 7500);
      const res2 = await fetch('forum.html');
      const data2 = await res2.text();
      if (data !== data2) {
        await ifThen();
        location.reload();
      }
    }
    

    阅读更多关于异步/等待here

    【讨论】:

    • 我认为您不了解异步函数的工作原理。
    • 你是对的,主线程没有被阻塞。因为它是一个微任务。
    猜你喜欢
    • 2013-04-21
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多