Search code examples
javascriptimpactjs

using timedelay function in javascript


I am trying to set my localStorage key values after a certain condition becomes true but wait for 2 seconds before it can update the localStorage key value

This is what I am trying to do but it throws an exception and when it tries to set the localStorage value

if(tempArray.length <= 0){                               
   setTimeout(function(){
       this.storage.set(achkey,1);                              
   },2000);                                   
}

The exception says variable achkey undefined though I can use it outside the setTimeout function. How do I go about implementing the delay and setting values inside correctly? I am using ImpactJS engine which uses javascript. I am also using a plugin for my localStorage.


Solution

  • You need to cache this. Once you enter the setTimeout's anonymous function, this now refers to the scope of the function that you just declared.

    if(tempArray.length <= 0){                               
       var self = this; // Cache the current scope's `this`
       setTimeout(function(){
           self.storage.set(achkey,1);                              
       },2000);                                   
    }