Drawing to a canvas based on user input
The short answer is that you can't, not really anyways. You have no real control over how this code will be compiled. Since you mention iPad, the code is likely to be JIT-compiled to bytecode, prior to execution. How this is done depends (in part) on how the code is written, and how JS is implemented. The second factor, the implementation, is beyond your control.

You're also working with a canvas element. That's not JS that causes the bottleneck there, that's the DOM, which is gouverned by W3C, and is not part of ECMAScript in any way. JS merely has an API, via which it can request the DOM to change state. The DOM API isn't all that good: it's badly designed, slow, counter intuitive and one of the main reasons why many people claim JS is a terrible language. JS isn't, it's the DOM. But I'm going off course.

Inside that loop, which repeats 3600 times, you're calling a function which isn't part of your post (perhaps provide the source for that). But my guess is, that this function interacts with the dom (perhaps moves something about). If so: request a repaint, using the requestAnimationFrame method, it makes a huge difference!

After that, to further optimize your code, use jslint. As the page says, it will hurt your feelings, but it's the best way to teach yourself some good practices, like not declaring 10001 vars seperatly, but using:

var i, j, another = 123, someArray = [], andAnObject = {};


The main bottleneck, however is putImageData. this JSPerf demonstrates an alternative, up to x5000 more performant alternative!
It uses a neat little trick to buffer the states: it draws from one canvas onto the other, which is a lot faster. As is loading the image, then using:

drawing_board_canvas_twod.getContext('2d').drawImage(image_data, pencil_begin_x, pencil_begin_y);


But the way the image_data is gotten in your code still relies on the horrid getImageData, which is outpaced even by getting the img data pixel-by-pixed. Perhaps refer to this question on StackOverflow and all linked pages for details...

For now, the next to last thing I'd suggest is: look into how you call this repeat function of yours. If it's called in response to an event, check to see if you can't, perhaps, delegate that event, eliminating any excess event listeners is always good for performance. Are you using libs like jQuery? Get rid of them if you can, because they are slower than VanillaJS, if you know how to write good vanillaJS, of course.

The last, but certainly not least important thing I'd suggest: never ever use globals. Globals are risky, slow, and make for hellish debugging: your code relies on global variables, because the repeat function starts of with:

if(device_type==0)


device_type is not declared in the scope of repeat, so that implies it being a global variable. Learn about closures, scopes and how to use them. It's what makes JS worth your while.