Le Qs Le Qs - 3 months ago 26
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


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


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);