Le Qs Le Qs - 1 month ago 5
Javascript Question

Executing some code when waiting for a timeout

I want to create a localstorage object before sometime has elapsed and destroy it after a certain time has elapsed.I plan on using the setTimeout method

setTimeout(function(){ localStorage.setItem("myobject", "wedding");
}, 20000);


I want to use an if statement to try and do that

var notYetTimeout;

if (notYetTimeout) {
//create the object before 20900 ms have elapsed
localStorage.setItem("myobject", "wedding");
}
else {
//destroy object after 2000ms have elapsed

localStorage.removeItem("myobject");
}


The code just shows you a rough idea and i wanted to know if this is possible in javascript.

Answer

I don't really understand the timings in your example, but hopefully you can get some use of the below example:

This will call setStorage after 1 sec and then call remStorage 3 sec after that.

function setStorage(key, val) {
  //localStorage.setItem(key, val);
  console.log('set storage ' + key);
  setTimeout(function() {
    remStorage('myobject');
  }, 3000);
}

function remStorage(key) {
  //localStorage.removeItem(key);
  console.log('removed storage ' + key);
}

setTimeout(function() {
  setStorage('myobject', 'wedding');
}, 1000);