添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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:

function git(limit) {
    var i = 0;
    var git = setInterval(function () {
        console.log(i);
        if (i === limit - 1) {
            clearInterval(git);
            return 'done';
    }, 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.

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');
    }, 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');
    }, 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 A but here it is scrambled and seems the defer runs all function not one after the other but simultaneously. That's why I asked this question because I want to return return defer; inside my 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;

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');
    }, 800);
git(5, function (x) {
  console.log(x);

Using a promise it would look like this:

function git(limit, callback) {
    var i = 0;
    return new Promise(function (resolve) {
        var git = setInterval(function () {
            console.log(i);
            if (i === limit - 1) {
                clearInterval(git);
                resolve('done');
        }, 800);
git(5)
  .then(function (x) {
    console.log(x);
    return new Promise(function (resolve) {
        setTimeout(function () { resolve("hello"); }, 1000);
  .then(function (y) {
    console.log(y); // "hello" after 1000 milliseconds

Edit: Added pseudo-example for promise creation

Edit 2: Using two promises

Edit 3: Fix promise.resolve

Well, you would have to use a promise and it would have to return that promise. But for this you have to find some library (most knows is probably Q). – Razem Jul 22, 2014 at 8:34 im trying to use promise() via new $.Deferred() but the problem is i want to execute the next function after the setinterval of first function is fully done. Right now when i do a().then(b()).then(c()); these functions contain same with the one i post above. – Vainglory07 Jul 22, 2014 at 8:35 Well, you can't call b and c. That's the spirit. ;-) It's just a().then(b).then(c) and it works this way: a returns a promise which is somehow resolved with a value x. This value is passed to the function b as a first parameter. The result of the b function (call it y) is then passed as a first parameter to the function c. And so on. An exception is when the b returns another promise. It would then just wait until this promise is resolved and then it would call c with the value of this promise. – Razem Jul 22, 2014 at 8:42 yes, it's working that way but my a, b, c has it's arguments that's why i put it as .then(a()), .then(b()) and i cannot just remove it. check my updated question. thank you for your help. – Vainglory07 Jul 22, 2014 at 8:52 Well, just wrap it in another function: func_a(3).then(function (x) { return func_b(5); }).then(function (y) { return func_a(2); }); – Razem Jul 22, 2014 at 8:57 if (i === limit - 1) { clearInterval(git); callback('done') // now call the callback function with 'done' }, 800); var x = git(5,console.log); // you passed the function you want to execute in second paramenter This should have been the accepted answer given the question in hand - albeit the Q that was accepted included a lot of extra / useful info it didn't really show the way to get the callback so that the value/result of the function being called could then be assigned to the var x as req.... (what 1 min difference makes when answering a Q - I see this is the gap that set the two answers aside from one another ! ☺☺♠♦☻♥◘•○ – JB-007 Dec 11, 2022 at 1:18

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.