Return value inside a setInterval

萝らか妹 提交于 2019-12-04 12:42:16

Do you expect it to wait until the interval ends? That would be a real pain for the runtime, you would block the whole page. Lots of thing in JS are asynchronous these days so you have to use callback, promise or something like that:

function git(limit, callback) {
    var i = 0;
    var git = setInterval(function () {
        console.log(i);
        if (i === limit - 1) {
            clearInterval(git);
            callback('done');
        }
        i++;
    }, 800);
}

git(5, function (x) {
  console.log(x);
});

Using a promise it would look like this:

function git(limit, callback) {
    var i = 0, promise = new Promise();
    var git = setInterval(function () {
        console.log(i);
        if (i === limit - 1) {
            clearInterval(git);
            promise.resolve('done');
        }
        i++;
    }, 800);

    return promise;
}

git(5)
  .then(function (x) {
    console.log(x);

    var promise = new Promise();
    setTimeout(function () { promise.resolve("hello"); }, 1000);

    return promise;
  })
  .then(function (y) {
    console.log(y); // "hello" after 1000 milliseconds
  });

Edit: Added pseudo-example for promise creation

Edit2: Using two promises

Try to get a callback to your git function.

function git(limit,callback) {
    var i = 0;
    var git = setInterval(function () {
        console.log(i);
        if (i === limit - 1) {
            clearInterval(git);
            callback('done') // now call the callback function with 'done'
        }
        i++;
    }, 800);
}

var x = git(5,console.log); // you passed the function you want to execute in second paramenter
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!