Search code examples
javascriptsettimeoutweb-worker

Using setTimeOut in a worker thread?


I'm trying to use a library that is realized by relying a lot on window.setTimeOut. I want to use it in a worker thread that doesn't have access to the windowscope.

Is it possible to use a polyfill or use any other method that does the same thing within this context?


Solution

  • You can use setTimeout (not setTimeOut) perfectly well. Just use it as global variable:

    setTimeout( ... stuff stuff stuff ..., number);
    

    And if you want to use global scope object for some reason, self is defined both in Browser and Web Worker:

    self.setTimeout( ... stuff stuff stuff ..., number);
    

    If a library is trying to access window, just define it to be global scope:

    self.window = self;
    window.setTimeout( ... stuff stuff stuff ..., number);
    

    If you have further doubts, please check this jsfiddle: https://jsfiddle.net/ryovLea1/1/