在setInterval函数中传递参数

    技术2025-07-18  8

    本文翻译自:Pass parameters in setInterval function

    Please advise how to pass parameters into a function called using setInterval . 请告知如何将参数传递给使用setInterval调用的函数。

    My example setInterval(funca(10,3), 500); 我的例子是setInterval(funca(10,3), 500); is incorrect. 是不正确的。


    #1楼

    参考:https://stackoom.com/question/1v6I/在setInterval函数中传递参数


    #2楼

    now with ES5, bind method Function prototype : 现在用ES5,bind方法函数原型:

    setInterval(funca.bind(null,10,3),500);

    Reference here 参考这里


    #3楼

    setInterval(function(a,b,c){ console.log(a + b +c); }, 500, 1,2,3); //note the console will print 6 //here we are passing 1,2,3 for a,b,c arguments // tested in node v 8.11 and chrome 69

    #4楼

    另一种解决方案在于传递你的函数(如果你有动态变量):setInterval('funca('+ x +','+ y +')',500);


    #5楼

    You can use a library called underscore js. 您可以使用名为underscore js的库。 It gives a nice wrapper on the bind method and is a much cleaner syntax as well. 它为bind方法提供了一个很好的包装器,也是一个更清晰的语法。 Letting you execute the function in the specified scope. 让您执行指定范围内的函数。

    http://underscorejs.org/#bind http://underscorejs.org/#bind

    _.bind(function, scope, *arguments) _.bind(函数,范围,*参数)


    #6楼

    setInterval(function,milliseconds,param1,param2,...)

    Update: 2018 - use the "spread" operator 更新:2018年 - 使用“传播”运算符

    function repeater(param1, param2, param3){ alert(param1); alert(param2); alert(param3); } let input = [1,2,3]; setInterval(repeater,3000,...input);

    Processed: 0.011, SQL: 9