Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value inside a setInterval

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';
        }
        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.

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 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;
}
like image 472
Vainglory07 Avatar asked Jul 22 '14 08:07

Vainglory07


People also ask

Which method receives the return value of setInterval () to?

5. Which method receives the return value of setInterval() to cancel future invocations? Explanation: Like setTimeout(), setInterval() returns a value that can be passed to clearInterval() to cancel any future invocations of the scheduled function.

Why you should not use setInterval?

In case of time intensive synchronous operations, setTimeInterval may break the rhythm. Also, if any error occurs in setInterval code block, it will not stop execution but keeps on running faulty code. Not to mention they need a clearInterval function to stop it.

What does setInterval return TypeScript?

Syntax of setInterval TypeScript arg1, arg2, arg3, … are the arguments passed to callback function. setInterval() function will return a non zero numeric that will identify created timer. It works similar to setTimeout() but executes callback repeatedly for each specific delay.

How do you escape setInterval?

Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.


2 Answers

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

like image 172
Razem Avatar answered Sep 26 '22 00:09

Razem


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
like image 40
Mritunjay Avatar answered Sep 23 '22 00:09

Mritunjay