javascript - window.onload called after returning from a event handler method -


this code learning purpose in javascript.i have declared global variable called num , initialized 30. increased on click of plus button , decreased on click of minus button.but when click plus button twice.it alerts 31 twice instead of showing 31 first 32.

when debugged on chrome found out breakpoint hits 'var num=30' again once executes increase method called onclick of plus button. why after return method window reloading?can please explain?thanks in advance.my code below :

window.onload =initialize; var num=30; function initialize() {  if(!document.getelementbyid) return;  var increasebutton = document.getelementbyid('plus'); increasebutton.onclick = increase; var decreasebutton = document.getelementbyid('minus'); decreasebutton.onclick = decrease;  }  function increase()  {     num++;     alert(num);   } function decrease()  {      num++;      alert(num);  } 

seems work me if html is:

<button type="button" id="plus">+</button> <button type="button" id="minus">-</button> 

you want decrease function be:

function decrease() {     num--;     alert(num); } 

jsfiddle: https://jsfiddle.net/ozymandiasii/l9h1xbsr/


Comments