0

Im implementing a stopwatch in salesforce. It runs fine if Im in the same time where the stopwatch is ticking(lets say tab a) but if I switch to another tab(lets say tab b ) for a while the time is not accurate when I return to the TAB A. I think that if i implement a worker function as a static resource I might achieve what Im hoping for i.e the clock to work accurately even Im working in TAB B. I tried to implement worker class but the code fails when entered into the worker resource. Here is the code

stopwatch.js

    start(event) {
            var worker = new Worker("/resource/webworker");
            worker.onmessage = function(e) {
            timeVal = e.data;
            console.log(e.data);
            };
    }
    

webworker.js

onmessage = function(e) {
 
    totalMilliseconds = 0;
    timeIntervalInstance;

        // Run timer code in every 1000 milliseconds
        this.timeIntervalInstance = setInterval(function() {

            // Time calculations for hours, minutes, seconds and milliseconds
            var hours = ( Array(2).join('0') + Math.floor((this.totalMilliseconds % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) ).slice( -2 );
            var minutes = ( Array(2).join('0') + Math.floor((this.totalMilliseconds % (1000 * 60 * 60)) / (1000 * 60)) ).slice( -2 );
            var seconds = ( Array(2).join('0') + Math.floor((this.totalMilliseconds % (1000 * 60)) / 1000) ).slice( -2 );

            // Output the result in the timeVal variable
            timeVal = hours + ":" + minutes + ":" + seconds;   
            this.totalMilliseconds += 1000;
            postMessage(timeVal);
        }, 1000);
  }

Im not good with javascript can anyone guide me what Im doing wrong here? Thank you.

1 Answer 1

2

Per the Locker API Viewer, you can't use any kind of worker. This feature is blocked because it cannot be regulated by Locker Service, and could pose a security risk. Instead, you might want to just record a time stamp of when the timer started, and again when it stops, so that you will have an accurate measurement of time. Alternatively, you'd have to use Visualforce in order to use a service worker.

3
  • is there any way other than worker using which i can keep the clock ticking even if im in another tab of the browser?
    – Tejas
    Commented Jun 15, 2021 at 2:58
  • @Tejas Keeping the start time in a variable is what I'd suggest. You could also use the performance api to keep markers and accurately determine how much time has elapsed.
    – sfdcfox
    Commented Jun 15, 2021 at 3:01
  • I will try that Thank you @sfdcfox
    – Tejas
    Commented Jun 15, 2021 at 6:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .