javascript - Run the count down or up function -



javascript - Run the count down or up function -

i wrote function count downwards or numbers pressing button. @ :

var timer; function counterfn(element,oldcount,newcount,speed) { if(isnan(speed)) speed=100; clearinterval(timer); if(oldcount===newcount) { element.text(newcount); return; } var counter=oldcount; timer=setinterval(function() { if(oldcount<newcount) { if(counter>newcount) clearinterval(timer); counter++; } else { if(counter<newcount) clearinterval(timer); counter--; } if(counter===newcount) { clearinterval(timer); } element.text(counter); },speed); } $('.button').on("click",function() { counterfn('.endelement',10,100,1); });

description of function attributes:

element : element show result oldcount : start number newcount : end number speed : repeat time of setinterval

now, according above code, if press element .button class, counterfn function run. if press button 1 time again (before clearing setinterval function), every thing ok.

this working demo : http://jsfiddle.net/hgh2hgh/gpvn9hcq/4/ can see, clicking on button, clear previous interval , run new one.

now if sec element phone call function :

$('.button2').on("click",function() { counterfn('.endelement2',50,70,2); });

naturally sec request stop timer , run new timer new attributes. cause global variable defined 1 setinterval.

look @ comments demolink of part : [1] in comments

if definition of variable within function, pressing button twice, mean running function 2 separate time.

look @ comments demolink of part : [2] in comments

ok, how run function correct?

thanks.

javascript setinterval countdown

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -