我试图在某个条件成立后设置我的 localStorage 键值,但等待 2 秒才能更新 localStorage 键值
这就是我想要做的,但当它尝试设置 localStorage 值时它会抛出异常
if(tempArray.length <= 0){
setTimeout(function(){
this.storage.set(achkey,1);
},2000);
}
异常表示变量 achkey 未定义,尽管我可以在 setTimeout 函数之外使用它。我该如何正确实现延迟并设置内部值?我正在使用 ImpactJS 引擎,它使用 javascript。我还在我的 localStorage 中使用了一个插件。
最佳答案
您需要缓存此
。输入 setTimeout
的匿名函数后,this
现在引用您刚刚声明的函数的作用域。
if(tempArray.length <= 0){
var self = this; // Cache the current scope's `this`
setTimeout(function(){
self.storage.set(achkey,1);
},2000);
}
关于javascript - 在javascript中使用时间延迟函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22821069/