为什么定时javascript重定向失败?

时间:2018-06-02 20:08:54

标签: javascript redirect

以下javascript重定向不起作用 - 页面只是不断请求目标URL,而计时器只是去负无穷大。 (注意我对没有javascript支持的客户端使用元刷新回退。)



 setInterval(function() {
     var span = document.querySelector("#counter");
     var count = span.textContent * 1 - 1;
     span.textContent = count;
     if (count <= 0) {
         window.location.replace("https://www.siliconharvest.com.au");
     }
 }, 1000);
&#13;
<!DOCTYPE html>
<html>
   <head>
      <noscript>
         <meta http-equiv="refresh" content="500" />
      </noscript>
   </head>
   <body>
      <!-- template from https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_redirect
         redirect guide https://davidwalsh.name/meta-refresh-javascript
         htaccess re-write: https://stackoverflow.com/questions/20154805/rewrite-all-urls-to-http-domain-com
         countdown redirect: https://stackoverflow.com/questions/3292038/redirect-website-after-certain-amount-of-time?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
         -->
      <p>We've been re-branded as "Silicon Harvest" and have moved to a new address!  The new URL is: <a href="https://www.siliconharvest.com.au">https://www.siliconharvest.com.au</a></p>
      <p>You will be redirected to the new address in <span id="counter" style="font-size:150%">5</span> seconds.</p>
      <p>If you are not redirected after 5 seconds, please click on the link above!</p>
     
   </body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

尝试在重定向之前停止间隔:

const timer = setInterval(function() {
     var span = document.querySelector("#counter");
     var count = span.textContent * 1 - 1;
     span.textContent = count;
     if (count <= 0) {
         clearInterval(timer);
         window.location.replace("https://www.siliconharvest.com.au");
     }
 }, 1000);
<!DOCTYPE html>
<html>
   <head>
      <noscript>
         <meta http-equiv="refresh" content="500" />
      </noscript>
   </head>
   <body>
      <!-- template from https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_redirect
         redirect guide https://davidwalsh.name/meta-refresh-javascript
         htaccess re-write: https://stackoverflow.com/questions/20154805/rewrite-all-urls-to-http-domain-com
         countdown redirect: https://stackoverflow.com/questions/3292038/redirect-website-after-certain-amount-of-time?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
         -->
      <p>We've been re-branded as "Silicon Harvest" and have moved to a new address!  The new URL is: <a href="https://www.siliconharvest.com.au">https://www.siliconharvest.com.au</a></p>
      <p>You will be redirected to the new address in <span id="counter" style="font-size:150%">5</span> seconds.</p>
      <p>If you are not redirected after 5 seconds, please click on the link above!</p>
     
   </body>
</html>