Le Qs Le Qs - 1 year ago 70
Javascript Question

Executing code while waiting for a timeout

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

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 20000 ms have elapsed
localStorage.setItem("myobject", "wedding");
} else {
//destroy object after 2000ms have elapsed

The code just shows you a rough idea and I want to know if this is possible in javascript?

Answer Source

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() {
  }, 3000);

function remStorage(key) {
  console.log('removed storage ' + key);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download