javascript 在 setInterval 中返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24882306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:30:19  来源:igfitidea点击:

Return value inside a setInterval

javascriptreturnsetinterval

提问by Vainglory07

I want to return a value inside a setInterval. I just want to execute something with time interval and here's what I've tried:

我想在 setInterval 中返回一个值。我只想以时间间隔执行某些操作,这是我尝试过的:

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

var x = git(5);
console.log(x);

And it's not working. Is there any other way?

它不起作用。有没有其他办法?

What I'm going to do with this is to do an animation for specific time interval. Then when i reached the limit (ex. 5x blink by $().fadeOut().fadeIn()), I want to return a value.

我要做的是为特定的时间间隔做一个动画。然后当我达到限制(例如5x blink by $().fadeOut().fadeIn())时,我想返回一个值。

This is the application:

这是应用程序

function func_a(limit) {
    var i = 0;
    var defer = $.Deferred();
    var x = setInterval(function () {
        $('#output').append('A Running Function ' + i + '<br />');

        if (i == limit) {
            $('#output').append('A Done Function A:' + i + '<br /><br />');
            clearInterval(x);
            defer.resolve('B');
        }
        i++;

    }, 500);
    return defer;
}

function func_b(limit) {
    var c = 0;
    var defer = $.Deferred();
    var y = setInterval(function () {
        $('#output').append('B Running Function ' + c + '<br />');

        if (c == limit) {
            $('#output').append('B Done Function B:' + c + '<br /><br />');
            clearInterval(y);
            defer.resolve('A');
        }
        c++;

    }, 500);
    return defer;
}

func_a(3).then( func_b(5) ).then( func_a(2) );

This is not functioning well, it should print A,A,A,Done A,B,B,B,B,B,Done B,A,A,Done Abut here it is scrambled and seems the defer runs all function not one after the otherbut simultaneously. That's why I asked this question because I want to return return defer;inside my if...

这运行不好,它应该打印,A,A,A,Done A,B,B,B,B,B,Done B,A,A,Done A但在这里它被打乱了,似乎是延迟runs all function not one after the other但同时。这就是我问这个问题的原因,因为我想回到return defer;我的内心if...

if (i == limit) {
     $('#output').append('A Done Function A:' + i + '<br /><br />');
     clearInterval(x);
     defer.resolve('B');
     // planning to put return here instead below but this is not working
     return defer;
}

回答by Razem

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:

您是否希望它等到间隔结束?这对运行时来说真的很痛苦,你会阻塞整个页面。现在 JS 中的很多东西都是异步的,所以你必须使用回调、promise 或类似的东西:

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

Edit2:使用两个承诺

回答by Mritunjay

Try to get a callbackto your gitfunction.

尝试获取callback您的git功能。

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