I want to execute simple code when user click on my button:
Your Loop is happening too fast for any result to be shown.
Everything is done but in about < 1ms. You could use timeouts to delay what's being shown so that you can see what's happening.
Edit: here is the JsFiddle Link: http://jsfiddle.net/4Bz27/9/
var progress = document.getElementById('progress');
var restoreCursor= function () {
document.body.style.cursor = 'default';
}
document.getElementById('gogogo').onclick = (function(){
document.body.style.cursor = 'wait';
var ii = 0;
// this is a immediately executed function
//that calls itself with a small timeout
(function goLoop(){
progress.textContent = ii;
if(ii<30000){
ii++;
setTimeout(goLoop,10);
}else {
restoreCursor();
}
})();
});
replace your jsFiddle by that and you're good to go.
personnally for better performance i would iterate over each frame. like this:
var ii =0;
(function goLoop(){
progress.textContent = ii;
if(ii>3000) {
ii++;
requestAnimationFrame(goLoop);
})();
Your styles are applied only after the call stack has finished. You can separate this into two different call stacks by running the second half of the function from a setInterval like this:
var progress = document.getElementById('progress');
document.getElementById('gogogo').onclick = (function(){
document.body.style.cursor = 'wait';
setTimeout(function(){
for(var ii = 0; ii < 30000; ii += 1){
progress.textContent = ii;
}
document.body.style.cursor = 'default';
}, 0);
});
RequestAnimationFrame Way
jsFiddle here
(function (W) {
W.onload = function () {
var D = W.document,
a = 0,
c = D.getElementById('progress');
function b() {
c.innerText = a + 1;
a++;
if (a < 500) {
requestAnimationFrame(b);
} else {
D.body.style.cursor = 'default';
}
}
function start() {
D.body.style.cursor = 'wait';
b()
}
D.getElementById('gogogo').onclick = start;
}
})(window)
This way you use less resources and so your complex link modification does not slow down other open websites.
You are performing a blocking operation. This will certainly cause slow script warnings at some point. You can solve this by making the loop asynchronous:
var progress = document.getElementById('progress');
document.getElementById('gogogo').onclick = (function(){
document.body.style.cursor = 'wait';
var index = 0,
updater;
updater = function() {
progress.textContent = index++;
if (index < 30000) {
setTimeout(updater, 50);
} else {
document.body.style.cursor = 'default';
}
};
updater();
});