是否可以将setTimeout函数存储在本地存储中? [英] Is it possible to store setTimeout function inside a localstorage?

查看:130
本文介绍了是否可以将setTimeout函数存储在本地存储中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提供下面的javascript代码.

Provided that I have the javascript code below.

var timeout = setTimeout(function(){
                alert('this is executed after 5 seconds');
              }, 5000);

localStorage.setItem('timeout_event', timeout);

我已经检查了setTimeout函数的返回值是id还是其他东西.如果用户刷新页面,如何重新运行超时事件?甚至有可能吗?

I have checked the return value of the setTimeout function to be an id or something. If the user refreshes the page, how do I re-run the timeout event? Is it even possible?

任何帮助都可以.预先谢谢你.

Any help will do. Thank you in advance.

推荐答案

我已经检查了setTimeout函数的返回值是id还是其他东西.

I have checked the return value of the setTimeout function to be an id or something.

是的,它是一个数字ID,您可以将其传递给clearTimeout以取消计划的函数运行.

Yes, it is a numeric id which you can pass to clearTimeout for cancelling a scheduled function run.

如果用户刷新页面,如何重新运行超时事件?

If the user refreshes the page, how do I re-run the timeout event?

是的,在卸载页面时,所有未完成的超时都将中止,因此您需要在新页面上重新启动超时.

Yes, when the page is unloaded all outstanding timeouts are aborted, so you'll need to restart the timeout on the new page.

有可能吗?

Is it even possible?

是,不是.您将无法运行从上一页安排的功能-它的所有上下文/作用域都将丢失-您需要在新页面的上下文中创建一个新功能.

Yes and no. You won't be able to run the function which you scheduled from the last page - all its context/scope would be lost - you need to create a new one, in the context of the new page.

但是,如果您要基于跨页面的超时/间隔执行某些功能,则可以使用

But if you want to execute certain functionalities based on a timeout/interval across pages, you can do so by using DOM storage or similar. You would store the timestamp of the designated function run, and a flag whether it has already run. That way, you can check on following pages whether and when you need to re-schedule the function.

这篇关于是否可以将setTimeout函数存储在本地存储中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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