-1

The problem

I am saving pictures in my IndexedDB on the browser. I want to call a function in javascript every 10 seconds to sync the URL's in the IndexedDB to my real database. It should be down in the backgroud. This means: There should be a function which will be called every 10 seconds to automaticall "sync" the entries in the database.

What i have done

I have already a "sync"-Button/functionality which works fine. This function should be called automatically. But this function in the background should not interrupt or distrubt my main functions in the foreground. For example adding new entries in the indexedDB.

During my research i found the folliwing function:

setInterval(function(){ alert("Hello"); }, 3000);    

But it just works alone and not parallel with my "main"-functions.

The ideal solution

The ideal solution should be a function (i have the function already) which will be triggered ever 10 seconds (it don't have to be really 10 seconds, this is just a sample number) but should not disurpt other functions by executing.

  • check this link and see how JS works...https://stackoverflow.com/q/21718774/6654503 – ivp Apr 01 '19 at 15:55
  • 3
    `setInterval` is exactly how you'd call something on an interval in the background. What exactly isn't working? – David Apr 01 '19 at 15:55
  • 2
    Also, you may want to investigate [websockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications). It's an interesting solution to problems like this. – random_user_name Apr 01 '19 at 15:59
  • Note the block on your script could be related to `alert()`. Just replace that by another logic (maybe `console.log("hello")` just to say something) and the interval function won't block your main script. Also note that `Javascript` is [single thread](https://www.red-gate.com/simple-talk/dotnet/asp-net/javascript-single-threaded/) – Shidersz Apr 01 '19 at 16:01
  • The answer depends on how long your background function runs. If it's short-living, `setInterval` will be fine, but if it does some lengthy processing, you might want to outsource it into a worker. Workers are physical threads, and are guaranteed not to interfere with the main UI thread. See https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers – georg Apr 01 '19 at 16:36

1 Answers1

1

If you just want to call your function again and again, try this code using setTimeInterval:

/* The data param is in case you want to pass some param */
var mySynFunc = (data) => {
    console.log(`Sync my data: ${data}`);
}

/* This id must be used to stop your function interval */
var id = setInterval(mySynFunc, 3000, 'my-url');

/* If you want to stop your setIntervalFunction use this */
clearInterval(id)
Esdras Xavier
  • 769
  • 1
  • 4
  • 12