如果我导航到另一个页面,setTimeout不起作用 [英] setTimeout doesn't work if i navigate to another page

查看:117
本文介绍了如果我导航到另一个页面,setTimeout不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在特定点击事件后10秒执行javascript。我使用 setTimeout

I was trying to execute a javascript 10 seconds after a particular click event.Hence i used setTimeout

setTimeout(function () {
    alert('hello');
}, 10000);

如果我在点击后在同一页面上,它可以工作。但是如果我导航到其他一些页面它不起作用。
因此,假设 setTimeout 适用于特定页面而非整个应用程序是正确的。

It works if i'm on the same page after the click.But if i navigate to some other page it doesn't work. So is it right to assume that setTimeout works with respect to a particular page and not the whole application.

有没有办法做我想要实现的目标。

Is there any way to do what i'm trying to achieve.

推荐答案

浏览器中发生的一切都是文件绑定。当您离开当前文档(页面)时,它会被废弃,包括计时器 - 正如预期的那样。

Everything that happens in the browser is document bound. When you navigate away from the current document (page) it becomes obsoleted including timers - as expected.

所以你在这里尝试的只是使用计时器是不可能的。

So what you try here is not possible just by using timers.

可以写一个 localStorage (或 sessionStorage )计时器启动时间和完成时间的项目,从新页面(如果它来自同一个原点),您读取项目并计算差异并启动新计时器(或添加参数为您导航到的网址的一部分。)

You can write a localStorage (or sessionStorage) item with time the timer started and when it should finish, and from the new page (provided it is from the same origin) you read the item and calculate the difference and start a new timer (or add the parameters as part of the url you navigate to).

这篇关于如果我导航到另一个页面,setTimeout不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆