user7718111
user7718111

Reputation:

Calling SetInterval function expressions

Ok so within my imgInt function I am calling another function "nextPhoto" from within. Although when I mouseOut of my image element I want to recall imgInt although I don't know what way to call it or if I may have to pass any parameters into it.

var imgInt = setInterval(function(){
    nextPhoto("next");
}, 2000);

image.addEventListener("mouseover", function(){
    clearInterval(imgInt);
    this.addEventListener("onmouseout", function(){
        setInterval(imgInt);
    }, false);
}, false);

Upvotes: 0

Views: 347

Answers (2)

Barmar
Barmar

Reputation: 782693

You can't restart a previous interval by passing it to setInterval. Define a function that starts the interval, and call that.

var imgInt;
function startInterval() {
    imgInt = setInterval(function(){
        nextPhoto("next");
    }, 2000);
}
startInterval();
image.addEventListener("mouseover", function() {
    clearInterval(imgInt);
});
image.addEventListener("mouseout", function() {
    startInterval();
});

It's almost always wrong to add one event listener inside another listener function, because it creates multiple listeners every time the first event occurs.

Upvotes: 1

Ricky Ruiz
Ricky Ruiz

Reputation: 26791

Just as a follow up on Mr. @Barmar answer.

The setInterval() method returns a unique interval ID (timeoutID).

The setInterval() method of the WindowOrWorkerGlobalScope mixin repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().

This method is expecing a Function as first parameter, followed by a delay in milliseconds and optionally N parameters which are passed through to the function passed as the first parameter once the timer expires.

var intervalID = scope.setInterval(func, delay[, param1, param2, ...]);

(function() {

  var imgInt,
    image = document.querySelector("img");

  function startInterval() {
    imgInt = setInterval(function(param1, param2) {
        //               ^^^^^^^  ^^^^^^  ^^^^^^ ^
        //              Function  param1  param2 N
        //nextPhoto("next");
        console.log(imgInt);
        //          ^^^^^^
        //     numeric timeoutID
        console.log(param1, param2);
        //          ^^^^^^  ^^^^^^
        //       "MyParam1"    2
      }, 2000,
      // ^^^^
      // delay
      "MyParam1", 2);
    // ^^^^^^    ^^^
    // param1   param2
  }
  image.addEventListener("mouseover", function() {
    clearInterval(imgInt);
  });
  image.addEventListener("mouseout", function() {
    startInterval();
  });
})();
<img src="//placehold.it/170?text=hover me" alt="Please mouseover this photo then mouseout wait 2 seconds then repeat.">

Upvotes: 0

Related Questions