I am a beginner, and I had a problem writing a pomodoro timer using js. Implemented it with setTimeout. Below is a piece of code that will work directly timer

function timer(){ var dataBefore = new Date().getTime(); if (timeNow > 0 && start === true){ timeNow-=100; $('#time').html(convertForUser(timeNow)); if (timeNow <= 0){ counter+=1; if (counter % 2 === 1){ timeNow = timeRest; $("#site-ico").attr("href", "/green.ico") $('.logo').html('<img src="/logo_rest.png" alt="logo"></img>'); } else{ timeNow = time; $("#site-ico").attr("href", "/red.ico") $('.logo').html('<img src="/logo_work.png" alt="logo"></img>'); } } var diff = (new Date().getTime() - dataBefore); } else{ return; } setTimeout(timer,(100-(diff*10))); } 

And everything seems to work adequately, but if you lose the focus, if you switch to another tab while the application is running, the execution of the code stops, the timer stops working. How can I solve this problem?

    1 answer 1

    In general, the point is that the browser lowers or pauses the activity in the inactive tabs, to solve this problem, use Web Workers that work in a separate thread from the UI.

    Specifically for your task there is a ready-made library https://www.npmjs.com/package/worker-timers