x秒后如何设置变量? [英] How to set a variable after x seconds?

查看:56
本文介绍了x秒后如何设置变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是在尝试完成以下任务.我希望它在页面加载后5秒钟将变量设置为true.

I'm basically trying to accomplish the following. I want it so 5 seconds after the page loads, it'll set the variable to true.

一旦为真,它将立即给出警报真".如果有人尝试在5秒钟前单击该按钮,则会将警报设置为假.

Once true, it'll proceed to give the alert "true".. for now. If someone tries to click the button before 5 seconds, it'll give the alert false.

推荐答案

您有正确的主意,但变量范围较小.为了减轻头痛,实际上最好避免使用 setTimeout 上的string eval选项(我知道,此方法在网络上的所有教程中都已显示),而是使用匿名函数:

You've got the right idea, but you have a minor issue with variable scope. To reduce headaches, it's really best to get away from using the string eval option on setTimeout (which is shown in tutorials all around the web, I know) and use an anonymous function:

var link;
function loading(){
    setTimeout(function(){ 
        link = true; 
    }, 5000);
}

这样,您将确切地知道 link 的声明位置,并且范围清晰.

This way, you'll know exactly where link is declared and the scope is crystal clear.

这篇关于x秒后如何设置变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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