0

Not sure if it is the best way to do it, but here's what I am trying:

Example Code:

$("#someElement").mouseout(function() {
    var firstLoop = setTimeout(function() {
        //do something
    }, 2000);

    setTimeout(function() {
        //do something else
    }, 4000);

    var timer = 1000;
    setTimeout(firstLoop, timer); //this doesn't works
});

I am trying to loop this infinitely.

6
  • A typo perhaps? timeout? Commented Mar 9, 2018 at 7:55
  • Are you looking for setInterval instead ? Commented Mar 9, 2018 at 7:57
  • Sorry, typo was only in my question. Commented Mar 9, 2018 at 7:57
  • @Striped tried setInterval also. Didn't work. Commented Mar 9, 2018 at 7:58
  • what is your goal? Commented Mar 9, 2018 at 8:01

2 Answers 2

1

setTimeout(firstLoop, timer); //this doesn't works

because setTimeout (firstLoop) doesn't return a function reference which setTimeout expects.

Make it

var firstLoop = function(){ 
  setTimeout(function() {
    //do something
  }, 2000);
}

From your comment

@arnoldemzi goal is to loop infinitely with both timeout, so, the first function then second then first then second.. and so on.

Just use setInterval

$("#someElement").mouseout(function() {
    var firstLoop = function() {
        console.log( "something" );
    };

    setTimeout(function() {
        //do something else
    }, 4000);

    var timer = 1000;
    setInterval(firstLoop, timer); //this doesn't works
});
Sign up to request clarification or add additional context in comments.

3 Comments

For your edit: Will that setInterval call setTimeout also?
@Saurabh No, there is no reason to. If you are looking for infinite looping, then keep it simple with setInterval.
Awesome, Understood.
0

You would use setInterval if you would like something to repeat on an interval, and pass it the function you'd like to repeat as well as the interval in milliseconds.

I've changed your code ever so slightly as to demonstrate this:

$('button').click(function() {

    var firstLoop = function() {
        console.log('first')
    };

    setTimeout(function() {
        console.log('second')
    }, 4000);

    var timer = 1000;
    setInterval(firstLoop, timer);
});

See a working fiddle here: https://jsfiddle.net/hgnm1mph/3/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.