Dec 9, 2020

JavaScript Async Event Handling Example

Preface

Recently I had a small issue related to JavaScript where events are kind of queued(assuming mousemove), while the event listener actually is a heavy-duty guy doing some time-consuming event.

Solution

I could come up with a small hacky stuff to call the actual heavy-work as later/async(using setTimeout) when an event is called.

The actual handler flags something to true to indicates, "hey, I'm working". So any next event(that would be produced far faster) will first check if there is an instance of the heavy-work first or not, then if there is no such thing, ask for starting a new.

This is the full sample code you may chek, but I would like to explain the interesting part.

canvas.addEventListener("mousemove",function(evt){
	console.log("mouse move evnt, x:"+evt.x + " , y:"+evt.y+ " busy: "+busy);
	if(busy){
		return;
	}
	busy = true;
	if(async_check.checked){
		setTimeout(function(){paint_dot(evt)},1);
	}else{
		paint_dot(evt);
	}

});
document.getElementById("clsbtn").addEventListener("click",clear);
function paint_dot(evt){
	busy = true;
	if(DELAY){
		for(var a =0 ;a <loop_c;a++){//simulating the heavy-work
			var e = document.createElement("span");
			e.innerHTML = a+"--";
			hidc.appendChild(e);
			e.parentNode.removeChild(e);
		}
	}
	g2.fillStyle = "#000000";
	g2.fillRect(evt.x*pixel_r,evt.y*pixel_r,3*pixel_r,3*pixel_r);
	busy = false;
}
code snippet 0: Sample javascript async event handler

Actually there is no any a real multithreading in js(too bad!), but the ability setTimeout() method is giving you would help you to come up with teh situations like this, the line setTimeout(function(){paint_dot(evt)},1); asks js "hey run it later, for now continue current function" is just like a semi-like threading.