How to stop executinf function after certain amount of time in JavaScript -
function avoidaftertime() { var starttime = new date().gettime(); var interval = setinterval(function () { if (new date().gettime() - starttime > 3000) { clearinterval(interval); console.log("more 2 sec") return; } longworking(); }, 2000); } avoidaftertime(); function longworking(){ var t; (i = 0; < 1e10; i++) t = i; console.log(t); }
hello. new js. need stop running function (here longworking) can executed few seconds or time. , want abort function in case of takes long. guess know how make using, example, threads in other programming language. have no idea making in js. thought in way (above)... doesn't work. can me?
hmm, drafted example. it's function runs every second , if takes more 6 seconds stop. can put work load in dosomething() function , let work every second , stop if takes long. or can stop based on value. depends on want it. used module pattern isolate logic , variables. can encapsulate logic in module way.
(function() { 'use strict'; let timing = 0; const interval = setinterval(dosomething, 1000); function dosomething() { timing++; if (timing > 5) { clearinterval(interval); } console.log('working'); } })();
is looking for?
Comments
Post a Comment