Timer Pattern in Javascript

Ankit Rana
Aug 26, 2017 · 3 min read

In javascript, we have a single thread that handles the UI update and javascript execution.I know their many threads like web worker but for UI and javascript, we have one single thread. So what happened if try to render the 10,000 record on HTML page using javascript. A common way is to for-each the each element and try to get one by one and add to DOM. but it causes a blocking to UI thread in the application, our UI doesn’t paint until all record gets inserted into DOM and that make the site unresponsive. So what are workarounds to solve this problem?

We use Timer pattern for this, I know two timer pattern that may help you to make your site responsive and render its data efficiently.

  • Asynchronous Timer Pattern
  • Recursive set timeout pattern

Before start explaining these two patterns, I am going to tell the most important function that is used in these two patterns. The setTimeout is function which executes it a callback function after the expiring the interval and only once.

setTimeout(callbackFunction, milliseconds, param1, param2, ...)

The minimum time interval is 4ms by design if you define 0 in millisecond parameter, it executes after 4 ms. This callback function is called after completion of the current execution of code in which timeout called because setTimeout function handled by a separate thread in our browser and when the time expires, it will push the callback function to callback queue.For the understanding of callback loop and execution lifecycle javascript, you should watch this video.

Asynchronous Execution Pattern

Splitting long-running code over setTimeout blocks releases the thread:

  • While processing a loop limit the scope to a small time window
  • Ensure that there is enough of a gap between timeouts restarting
var demoArray = [];
for (var i = 1; i <= 1000; i++) {
demoArray.push(1 + Math.floor(Math.random() * 50));
}

$(document).ready(function() {

var buffer = function(items, iterFunction, callback) {
var i = 0.
len = items.length;

setTimeout(function() {
var result;
// +new Date returns the number of milliseconds
//((+new Date) - start < 50 => buffer of 50 milliseconds
for (var start = +new Date; i < len && result !== false && ((+new Date) - start < 50); i++) {
result = iterFunction.call(items[i], items[i], i);
}

/* callee is a property of the arguments object. It can be used to refer to the currently executing function inside the function body of that function. This is for example useful when you don't know the name of this function, which is for example the case with anonymous functions. */
if (i < len && result !== false) {
setTimeout(arguments.callee, 20);
} else {
callback();
}

}, 20);
};

var html = '';
buffer(demoArray, function(item) {
html += '<li>' + item + '</li>';
}, function() {
$('ul').append(html);
});
});

Recursive setTimeout pattern

The Recursive setTimeout pattern is most commonly used when we want periodically running a piece of functionality, related to duration (most commonly used to query a data source).This may sound like what setInterval does, but there is a problem with using setInterval. Because JavaScript is asynchronous, the setInterval method actually does not wait for the previous function to finish its execution before begins the next time period. What if the function was waiting for an AJAX response? Function execution can get out of order.

So, the idea is to use setTimeout. setTimeout can ensure the order of execution:

$(document).ready(function() {

setTimeout(function getDate() {

$get('someUrl', function(date) {

setTimeout(getDate, 5000);

});
}, 5000);
});

Thanks, for reading! :)

Originally published at www.codeatom.in on August 26, 2017.

)
Ankit Rana

Written by

I am Code Writer, dreamer :), java-script developer and Architecture enthusiastic.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade