4

I have a vimeo video that I want to play 3 seconds after a button is clicked. I can get the video to play on click, but I can't seem to get the setTimeout in the right spot... any suggestions?

var iframe1 = document.getElementById("prelearn-1");
var player1 = $f(iframe1);

var prelearnBtn = document.getElementById("prelearn-1-btn");
prelearnBtn.addEventListener("click", setTimeout(function(){player1.api("play")}, 3000));

I'm using the vimeo froogaloop API.

aRig
  • 45
  • 1
  • 1
  • 3

4 Answers4

15

Just wrap it inside a function -

prelearnBtn.addEventListener("click", function(){
    setTimeout(function(){
        player1.api("play");
    }, 3000);
});
SachinGutte
  • 6,947
  • 5
  • 35
  • 58
2

The setTimeout function takes in a callback function. Just wrap your code in an anonymous function, then it should work. Also, you might have cross-domain issues if you're attempting to access the contents of an iFrame.

var iframe1 = document.getElementById("prelearn-1");
var player1 = $f(iframe1);

var prelearnBtn = document.getElementById("prelearn-1-btn");
prelearnBtn.addEventListener("click", function(){setTimeout(function(){player1.api("play")}, 3000)});
andrewgu
  • 1,562
  • 14
  • 23
0

AddEventlistener takes anonymous function as the second argument. So you need to wrap the setTimeout inside the anonymous function. Whenever the click event happens, the setTimeout code will trigger and will play the video.

prelearnBtn.addEventListener("click", function () {
    setTimeout(function () {
        player1.api("play")
    }, 3000)
}, false);
mohamedrias
  • 18,326
  • 2
  • 38
  • 47
0

ES2015 shorter syntax + utilizing the 3rd argument of the setTimeout will make our code shorter and nicer while keeping it readiable:

document.querySelector('button').addEventListener("click",() => 
  setTimeout(console.log, 1000, "play")
)
<button>Play</button>

The above example replaced OP's player1.api method with console.log for the sake of printing the argument, which illustrate the code works.

vsync
  • 118,978
  • 58
  • 307
  • 400