javascript - Stoppping synchronous function after 2 seconds -
i'm using npm library jsdiff, has function determines difference between 2 strings. synchronous function, given 2 large, different strings, take extremely long periods of time compute.
diff = jsdiff.diffwords(article[revision_comparison.field], content[revision_comparison.comparison]);
this function called in stack handles request through express. how can i, sake of user, make experience more bearable? think 2 options are:
- cancelling synchronous function somehow.
- cancelling user request somehow. (but keep function still running?)
edit: should note given 2 large , different strings, want different logic take place in code. therefore, waiting process finish unnecessary , cumbersome on load - don't want run long period of time.
i found on jsdiff's repository:
all methods above accept optional callback method run in sync mode when parameter omitted , in async mode when supplied. allows larger diffs without blocking event loop. may passed either directly final parameter or callback field in options object.
this means should able add callback last parameter, making function asynchronous. this:
jsdiff.diffwords(article[x], content[y], function(err, diff) { //add whatever need });
now, have several choices:
return directly user , keep function running in background.
set 2 second timeout (or whatever limit fits application) using settimeout outlined in answer.
if go option 2, code should this
jsdiff.diffwords(article[x], content[y], function(err, diff) { //add whatever need return callback(err, diff); }); //if called, means above operation took more 2000ms (2 seconds) settimeout(function() { return callback(); }, 2000);
Comments
Post a Comment