javascript - Creating a "delay" function in JS? -
i've been reading settimeout , other such timers. i'm wondering if it's possible work custom function need this:
//code delay(time); //more code
is possible?
update: ok, kind of it. if isn't reasonably possible, how go delaying loop after first time. want run upon execution delay on each iteration afterward.
new update: figure since initial thought fell through, might easier show code have.
function autofarm (clickevent){ var farmtargets = [ "6_300_1", "6_300_3", "6_300_4", "6_300_5", "6_300_7"]; settimeout(function() { $.each (farmtargets, function(index, target){ var extradata = '{"end_pos":"' + target + '","purpose":0,"upshift":1,"bring_res":{"0":0,"2":0,"1":0},"bring_ship":{"1":25,"11":0},"rate":100,"start_pos":"6_300_2"}'; var finaldata = basedatadora + extradata + "&type=1"; settimeout(function(){ (i = 0; < farmtargets.length; i++){ postrequest(sendfleeturl + getsign(extradata). finaldata, function(json){ }); } }, 15000); });//end each loop }, 1320000); }//end autofarm
basically, should execute , run loop 5 times on first array element 15 seconds apart. 22 minutes later move next set , repeat entire array.
you can achieve along lines generators. idea continuation passing style (callback hell) can flattened. generator uses yield
keyword pause function, until callback resumes calling next
method:
var async = function(gen) { var g = gen() function next(x) { var cur = g.next(x) if (cur.done) { return cur.value } cur.value(next) } next() } var delay = function(time) { return function(f) { settimeout(f, time) } } async(function* () { console.log('before') yield delay(1000) // waits 1 second console.log('middle') yield delay(1000) // waits 1 second console.log('after') })
in cps read like:
console.log('before') settimeout(function() { console.log('middle') settimeout(function() { console.log('after') }, 1000) }, 1000)
this works in chrome, firefox , iojs today.
Comments
Post a Comment